Go

Go

Made by DeepSource

Missing an optimization opportunity when indexing maps by byte slices SCC-SA6001

Performance
Major
Autofix

Map keys must be comparable, which precludes the use of byte slices. This usually leads to using string keys and converting byte slices to strings.

Usually, converting a byte slice to a string needs to copy the data and causes allocations. The compiler, however, recognizes m[string(b)] and uses the data of b directly, without copying it, because it knows that the data can't change during the map lookup.

Bad practice

k := string(b) // copies and allocates
println(m[k])
println(m[k])

Recommended

println(m[string(b)])
println(m[string(b)])

References