When you have 2 keys for a value, 1d or 2d map should you use?
The topic was found during optimization. When 2 string type keys indicate a value, how do you maintain the mapping? Generally we can come up with 3 approaches listed below:
type Result string
// 1d map, you need to concatenate 2 strings
var d1M map[string]Result
// 1d map and use struct as key
type Key struct {
S1, S2 string
}
var d1MS map[Key]Result
// 2d map
var d2M map[string]map[string]Result
The 1d mapping needs pay for the string concatenation, the 2d mapping is required for an additional map query per query and the 1d map with struct key requires additional calculation on map.
The conclusion is 2d map is fastest because string concatenation costs more. What's worse, inappropriate string concatenations causes higher memory usages and triggers more GC(result got from pprof). It has been verified in the real practice by my teammates as well.
Note that here the keys are string. If they're small integers we can consider to use bit operation to append them together. Hence, we can finish the map querying in 1 operation.
This blog is not intended to analyze which method to append string(fmt.Sprintf
, +
, strings.Builder
, etc...) is better and why it's fastest. It shows the result only.