当前位置: 首页 > 工具软件 > murmur3 > 使用案例 >

golang哈希算法性能对比md5,crc32,sha1,murmur3

颜华池
2023-12-01
package main

import (
	"crypto/md5"
	"crypto/sha1"
	"hash/crc32"

	"github.com/spaolacci/murmur3"
)

var str = "hello world"

func md5Hash() [16]byte {
	return md5.Sum([]byte(str))
}

func sha1Hash() [20]byte {
	return sha1.Sum([]byte(str))
}

func crc32Hash() uint32 {
	return crc32.ChecksumIEEE([]byte(str))
}

func murmur32Hash() uint32 {
	return murmur3.Sum32([]byte(str))
}

func murmur64Hash() uint64 {
	return murmur3.Sum64([]byte(str))
}
package main

import (
	"testing"
)

func BenchmarkMd5(b *testing.B) {
	for i := 0; i < b.N; i++ {
		md5Hash()
	}
}

func BenchmarkSha1(b *testing.B) {
	for i := 0; i < b.N; i++ {
		sha1Hash()
	}
}

func BenchmarkCrc32(b *testing.B) {
	for i := 0; i < b.N; i++ {
		crc32Hash()
	}
}

func BenchmarkMur32(b *testing.B) {
	for i := 0; i < b.N; i++ {
		murmur32Hash()
	}
}

func BenchmarkMur64(b *testing.B) {
	for i := 0; i < b.N; i++ {
		murmur64Hash()
	}
}

> go test -bench=. -benchmem
goos: windows
goarch: amd64
pkg: hashcompare
cpu: Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz
BenchmarkMd5-8           9954531               120.2 ns/op             0 B/op          0 allocs/op
BenchmarkSha1-8          7564730               157.4 ns/op             0 B/op          0 allocs/op
BenchmarkCrc32-8        24542084                46.63 ns/op           16 B/op          1 allocs/op
BenchmarkMur32-8        73686084                15.76 ns/op            0 B/op          0 allocs/op
BenchmarkMur64-8        26042966                44.21 ns/op           16 B/op          1 allocs/op
PASS
ok      hashcompare     6.294s

可见murmur3要比md5sha1要快很三倍多。

 类似资料: