Skip to content

Instantly share code, notes, and snippets.

@Deleplace
Last active September 9, 2022 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deleplace/e60f6170fc82b60c3db3dc57a4c711b4 to your computer and use it in GitHub Desktop.
Save Deleplace/e60f6170fc82b60c3db3dc57a4c711b4 to your computer and use it in GitHub Desktop.
Comparison of memory footprint of map[int]bool vs. map[int]struct{}
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
@Deleplace
Copy link
Author

Output on my workstation ():

% go run ./set_implementations.go

set as map[int]bool
HeapAlloc is 141792 bytes
HeapAlloc is 115691680 bytes

set as map[int]struct{}
HeapAlloc is 142184 bytes
HeapAlloc is 105865088 bytes

In this examples, bool values use 9% more memory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment