Performance of byte-arrays as map keys

795 views
Skip to first unread message

Amit Lavon

unread,
Mar 26, 2023, 6:05:52 AM3/26/23
to golang-nuts
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

Keith Randall

unread,
Mar 27, 2023, 10:50:02 AM3/27/23
to golang-nuts
Key sizes 4 and 8 have special case hashing code.
They are intended for int32, int64, and pointers, but your [4]byte and [8]byte take advantage of it as well.

Amit Lavon

unread,
Mar 29, 2023, 2:51:04 PM3/29/23
to golang-nuts
Thank you! Now it makes sense to me.

Andrew Hodel

unread,
Dec 15, 2025, 12:54:41 PM (22 hours ago) Dec 15
to golang-nuts
The map still iterates through the keys if it's a string.

You could expect sizes though, but you should still use `map[*[]byte]`.




Andrew

Reply all
Reply to author
Forward
0 new messages