diff --git a/blake3.go b/blake3.go index 9b33d93..91ac71f 100644 --- a/blake3.go +++ b/blake3.go @@ -406,9 +406,13 @@ func New(size int, key []byte) *Hasher { return newHasher(keyWords, flagKeyedHash, size) } +// Sum256 and Sum512 always use the same hasher state, so we can save some time +// when hashing small inputs by constructing the hasher ahead of time. +var defaultHasher = newHasher(iv, 0, 0) + // Sum256 returns the unkeyed BLAKE3 hash of b, truncated to 256 bits. func Sum256(b []byte) (out [32]byte) { - h := newHasher(iv, 0, 0) + h := *defaultHasher h.Write(b) h.XOF().Read(out[:]) return @@ -416,7 +420,7 @@ func Sum256(b []byte) (out [32]byte) { // Sum512 returns the unkeyed BLAKE3 hash of b, truncated to 512 bits. func Sum512(b []byte) (out [64]byte) { - h := newHasher(iv, 0, 0) + h := *defaultHasher h.Write(b) h.XOF().Read(out[:]) return diff --git a/blake3_test.go b/blake3_test.go index 7db3605..fdf0ed7 100644 --- a/blake3_test.go +++ b/blake3_test.go @@ -195,11 +195,27 @@ func BenchmarkWrite(b *testing.B) { } func BenchmarkSum256(b *testing.B) { - b.ReportAllocs() - buf := make([]byte, 1024) - for i := 0; i < b.N; i++ { - blake3.Sum256(buf) - } + b.Run("64", func(b *testing.B) { + b.ReportAllocs() + buf := make([]byte, 64) + for i := 0; i < b.N; i++ { + blake3.Sum256(buf) + } + }) + b.Run("1024", func(b *testing.B) { + b.ReportAllocs() + buf := make([]byte, 1024) + for i := 0; i < b.N; i++ { + blake3.Sum256(buf) + } + }) + b.Run("65536", func(b *testing.B) { + b.ReportAllocs() + buf := make([]byte, 65536) + for i := 0; i < b.N; i++ { + blake3.Sum256(buf) + } + }) } func BenchmarkXOF(b *testing.B) {