Skip to content

Instantly share code, notes, and snippets.

@hectorj
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save hectorj/8ac959c071d44ec4d718 to your computer and use it in GitHub Desktop.

Select an option

Save hectorj/8ac959c071d44ec4d718 to your computer and use it in GitHub Desktop.
Bench of several hash algorithms for cache keys in golang
package cachekeyhash_test
import (
"crypto/sha256"
"fmt"
"hash/fnv"
"io"
"testing"
"crypto/md5"
"crypto/sha1"
)
func hashKey(key string) string {
h := sha256.New()
io.WriteString(h, key)
return fmt.Sprintf("%x", h.Sum(nil))
}
func hashKey2(key string) string {
h := sha256.New()
h.Write([]byte(key))
return fmt.Sprintf("%x", h.Sum(nil))
}
func hashKeyFNV(key string) string {
h := fnv.New64a()
io.WriteString(h, key)
return fmt.Sprintf("%x", h.Sum(nil))
}
func hashKeyFNV2(key string) string {
h := fnv.New64a()
h.Write([]byte(key))
return fmt.Sprintf("%x", h.Sum(nil))
}
func hashKeyMD52(key string) string {
h := md5.New()
h.Write([]byte(key))
return fmt.Sprintf("%x", h.Sum(nil))
}
func hashKeySHA1(key string) string {
h := sha1.New()
h.Write([]byte(key))
return fmt.Sprintf("%x", h.Sum(nil))
}
func BenchmarkHashKeySha256(b *testing.B) {
for i := 0; i < b.N; i++ {
hashKey("GET:http://localhost/")
}
}
func BenchmarkHashKeyFNV(b *testing.B) {
for i := 0; i < b.N; i++ {
hashKeyFNV("GET:http://localhost/")
}
}
func BenchmarkHashKey2Sha256(b *testing.B) {
for i := 0; i < b.N; i++ {
hashKey2("GET:http://localhost/")
}
}
func BenchmarkHashKey2FNV(b *testing.B) {
for i := 0; i < b.N; i++ {
hashKeyFNV2("GET:http://localhost/")
}
}
func BenchmarkHashKey2MD5(b *testing.B) {
for i := 0; i < b.N; i++ {
hashKeyMD52("GET:http://localhost/")
}
}
func BenchmarkHashKey2SHA1(b *testing.B) {
for i := 0; i < b.N; i++ {
hashKeySHA1("GET:http://localhost/")
}
}
FNV 2000000 760 ns/op 121 B/op 7 allocs/op
MD5 1000000 1327 ns/op 266 B/op 8 allocs/op
SHA1 1000000 1608 ns/op 378 B/op 9 allocs/op
Sha256 1000000 1992 ns/op 412 B/op 9 allocs/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment