Skip to content

Instantly share code, notes, and snippets.

@adityasonel
Last active April 24, 2020 08:26
Show Gist options
  • Save adityasonel/c6e7938bf01660a8b7593cf0bc2a56bb to your computer and use it in GitHub Desktop.
Save adityasonel/c6e7938bf01660a8b7593cf0bc2a56bb to your computer and use it in GitHub Desktop.
Benchmarks test to know how much memory can be saved by using struct{} instead of booleans.
package main
import (
"fmt"
"testing"
)
func benchmarkBooleans(b *testing.B) {
s := make(map[int]bool)
for i := 0; i < 1000*b.N; i++ {
s[2*i] = true
}
}
func benchmarkStructs(b *testing.B) {
s := make(map[int]struct{})
for i := 0; i < 1000*b.N; i++ {
s[2*i] = struct{}{}
}
}
func main() {
boolRes := testing.Benchmark(benchmarkBooleans)
fmt.Println("booleans:", boolRes.MemString())
structRes := testing.Benchmark(benchmarkStructs)
fmt.Println("structs{}:", structRes.MemString())
fmt.Println("ratio:", float32(boolRes.AllocedBytesPerOp()) / float32(structRes.AllocedBytesPerOp()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment