Hi gophers,
Some code I am writing uses byte-arrays ([X]byte) as keys in a map. I benchmarked the performance of map operations using different X's and found that 4 and 8 are about twice as fast compared to 5, 6, 7 (see below).
Can someone explain this phenomenon?
I'd like to learn about it so I can take it in consideration when choosing key types.
Code:
type byteArray interface {
[4]byte | [5]byte | [6]byte | [7]byte | [8]byte
}
func benchmarkMaps[T byteArray](b *testing.B) {
m := map[T]int{}
var t T
for i := 0; i < b.N; i++ {
m[t]++
}
}
func BenchmarkMaps(b *testing.B) {
b.Run("4", benchmarkMaps[[4]byte])
b.Run("5", benchmarkMaps[[5]byte])
b.Run("6", benchmarkMaps[[6]byte])
b.Run("7", benchmarkMaps[[7]byte])
b.Run("8", benchmarkMaps[[8]byte])
}
Results:
4: 17.01 ns/op
5: 36.02 ns/op
6: 38.24 ns/op
7: 29.92 ns/op
8: 16.58 ns/op
go1.20