Skip to content

Instantly share code, notes, and snippets.

@C-Pro
Created March 25, 2023 07:52
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 C-Pro/d7018fc12ad31f08f890e72e5ffec32a to your computer and use it in GitHub Desktop.
Save C-Pro/d7018fc12ad31f08f890e72e5ffec32a to your computer and use it in GitHub Desktop.
Compare allocation size for different type of map values for "set" type containers, where only the keys are of any interest.
package main_test
import "testing"
func BenchmarkBoolMap(b *testing.B) {
m := map[int]bool{}
for i := 0; i < b.N; i++ {
m[i] = true
}
}
func BenchmarkEmptyStructMap(b *testing.B) {
m := map[int]struct{}{}
for i := 0; i < b.N; i++ {
m[i] = struct{}{}
}
}
func BenchmarkEmptyInterfaceMap(b *testing.B) {
m := map[int]interface{}{}
for i := 0; i < b.N; i++ {
m[i] = nil
}
}
@C-Pro
Copy link
Author

C-Pro commented Mar 25, 2023

Empty struct is the winner:

$ go test -v -bench=. -benchmem .
goos: linux
goarch: amd64
cpu: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
BenchmarkBoolMap
BenchmarkBoolMap-8               4379631               296.6 ns/op            50 B/op          0 allocs/op
BenchmarkEmptyStructMap
BenchmarkEmptyStructMap-8        5033970               256.1 ns/op            39 B/op          0 allocs/op
BenchmarkEmptyInterfaceMap
BenchmarkEmptyInterfaceMap-8     3737322               376.0 ns/op           132 B/op          0 allocs/op
PASS
ok      _/home/cpro/work/experiments/mapbench   5.852s

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