Created
January 4, 2020 14:50
-
-
Save hnakamur/b38f644ef745454462a9542558c6bdfc to your computer and use it in GitHub Desktop.
Example for passing pre-allocated buf to hash.Sum(b []byte) in Go
This file contains 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
$ go test -bench=. -benchmem | |
goos: linux | |
goarch: amd64 | |
BenchmarkHashNewSum-2 5807700 205 ns/op 112 B/op 2 allocs/op | |
BenchmarkHashNewSum2-2 8323488 142 ns/op 0 B/op 0 allocs/op | |
BenchmarkHashSum-2 8817842 134 ns/op 0 B/op 0 allocs/op | |
BenchmarkHashSum2-2 7696573 155 ns/op 16 B/op 1 allocs/op | |
PASS | |
ok _/home/hnakamur/hash-benchmark 5.402s | |
$ go version | |
go version go1.13.5 linux/amd64 |
This file contains 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
package sum | |
import ( | |
"crypto/md5" | |
"testing" | |
) | |
var input = []byte("あめんぼあかいなあいうえお") | |
func BenchmarkHashNewSum(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
hash := md5.New() | |
hash.Write(input) | |
buf := hash.Sum(nil) | |
dummy(buf) | |
} | |
} | |
func BenchmarkHashNewSum2(b *testing.B) { | |
hash := md5.New() | |
buf := make([]byte, md5.Size) | |
for i := 0; i < b.N; i++ { | |
hash.Write(input) | |
buf = hash.Sum(buf) | |
dummy(buf) | |
buf = buf[:0] | |
hash.Reset() | |
} | |
} | |
func BenchmarkHashSum(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = md5.Sum(input) | |
} | |
} | |
func BenchmarkHashSum2(b *testing.B) { | |
var buf []byte | |
for i := 0; i < b.N; i++ { | |
s := md5.Sum(input) | |
buf = s[:] | |
} | |
dummy(buf) | |
} | |
func dummy(buf []byte) {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment