Last active
April 24, 2020 08:26
-
-
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.
This file contains hidden or 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" | |
"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