packagemainimport ("runtime")typedatastruct { i, j int}funcmain() {var N =40000000var structure []datafor i :=0; i < N; i++ { value :=int(i) structure =append(structure, data{value, value}) } runtime.GC() _ = structure[0]}
Using a map with pointers
packagemainimport ("runtime")funcmain() {var N =40000000 myMap :=make(map[int]*int)for i :=0; i < N; i++ { value :=int(i) myMap[value] =&value } runtime.GC() _ = myMap[0]}
Using a map without pointers
packagemainimport ("runtime")funcmain() {var N =40000000 myMap :=make(map[int]int)for i :=0; i < N; i++ { value :=int(i) myMap[value] = value } runtime.GC() _ = myMap[0]}
Splitting the map
The implementation of this subsection will split the map into a map of maps, which is also called sharding. The program of this subsection is saved as mapSplit.go and will be presented in two parts
packagemainimport ("runtime")funcmain() {var N =40000000 split :=make([]map[int]int, 200)for i :=range split { split[i] =make(map[int]int) }for i :=0; i < N; i++ { value :=int(i) split[i%200][value] = value } runtime.GC() _ = split[0][0]}
Results
What will be important in the presented output is not the exact numbers but the time difference between the four different approaches.
$ time go run main.goUsing plain slices real 0m1.058suser 0m1.319ssys 0m0.301sUsing map with pointersreal 0m15.667suser 0m27.961ssys 0m1.722sUsing map without pointerreal 0m15.667suser 0m27.961ssys 0m1.722sSpliting mapreal 0m9.349suser 0m8.636ssys 0m0.826s