Last active
September 9, 2022 16:41
-
-
Save Deleplace/e60f6170fc82b60c3db3dc57a4c711b4 to your computer and use it in GitHub Desktop.
Comparison of memory footprint of map[int]bool vs. map[int]struct{}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"runtime" | |
) | |
func main() { | |
BoolImplMemoryFootprint() | |
EmptyStructImplMemoryFootprint() | |
} | |
type setbool map[int]bool | |
func BoolImplMemoryFootprint() { | |
fmt.Println() | |
fmt.Println("set as map[int]bool") | |
M := 20_000 | |
K := 300 | |
Sink = nil | |
showMem() | |
rng := rand.New(rand.NewSource(42)) | |
a := make([]setbool, K) | |
for i := range a { | |
m := make(setbool, M) | |
for k := 0; k <= M; k++ { | |
if rng.Intn(2) == 1 { | |
m[k] = true | |
} | |
} | |
a[i] = m | |
} | |
showMem() | |
Sink = a | |
} | |
type setstruct map[int]struct{} | |
func EmptyStructImplMemoryFootprint() { | |
fmt.Println() | |
fmt.Println("set as map[int]struct{}") | |
M := 20_000 | |
K := 300 | |
Sink = nil | |
showMem() | |
rng := rand.New(rand.NewSource(42)) | |
a := make([]setstruct, K) | |
for i := range a { | |
m := make(setstruct, M) | |
for k := 0; k <= M; k++ { | |
if rng.Intn(2) == 1 { | |
m[k] = struct{}{} | |
} | |
} | |
a[i] = m | |
} | |
showMem() | |
Sink = a | |
} | |
func showMem() { | |
runtime.GC() | |
var memstat runtime.MemStats | |
runtime.ReadMemStats(&memstat) | |
fmt.Println("HeapAlloc is", memstat.HeapAlloc, "bytes") | |
} | |
var Sink any |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output on my workstation ():
In this examples, bool values use 9% more memory.