perf: reduce unnecessary allocations in NewSHA1 and NewMD5#181
Closed
anatoly-kussul wants to merge 1 commit intogoogle:masterfrom
anatoly-kussul:hash-allocs
Closed
perf: reduce unnecessary allocations in NewSHA1 and NewMD5#181anatoly-kussul wants to merge 1 commit intogoogle:masterfrom anatoly-kussul:hash-allocs
anatoly-kussul wants to merge 1 commit intogoogle:masterfrom
anatoly-kussul:hash-allocs
Conversation
anatoly-kussul
commented
Jan 6, 2025
Contributor
|
Would you get the same speedup if NewHas as not public (e.g., newHash)? |
Author
Doesn't seem like so. func newHash(h hash.Hash, space UUID, data []byte, version int) UUID {
h.Reset()
h.Write(space[:]) //nolint:errcheck
h.Write(data) //nolint:errcheck
s := h.Sum(nil)
var uuid UUID
copy(uuid[:], s)
uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4)
uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 9562 variant
return uuid
}
func NewSHA1(space UUID, data []byte) UUID {
return newHash(sha1.New(), space, data, 5)
}produces while func newHash(_ hash.Hash, space UUID, data []byte, version int) UUID {
h := sha1.New()
h.Write(space[:]) //nolint:errcheck
h.Write(data) //nolint:errcheck
s := h.Sum(nil)
var uuid UUID
copy(uuid[:], s)
uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4)
uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 9562 variant
return uuid
}
func NewSHA1(space UUID, data []byte) UUID {
return newHash(nil, space, data, 5)
}already gets it down to last allocation comes from s := h.Sum(nil)changing that to slice with compile-time known cap removes last allocation s := h.Sum(make([]byte, 0, sha1.Size))and gets |
bormanp
approved these changes
Jan 6, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.