Skip to content

Instantly share code, notes, and snippets.

@chaudum
Created March 30, 2023 07:42
Show Gist options
  • Save chaudum/e035f31cdeb2d9aa98bd03450fa3042f to your computer and use it in GitHub Desktop.
Save chaudum/e035f31cdeb2d9aa98bd03450fa3042f to your computer and use it in GitHub Desktop.
int map vs *int map
$ gotest -v ./ -bench=Benchmark -test.run=^$ -benchtime=100000000x
goos: linux
goarch: amd64
pkg: maptest
cpu: 11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz
BenchmarkIntMap
BenchmarkIntMap-8 100000000 55.85 ns/op 0 B/op 0 allocs/op
BenchmarkIntPointerMap
BenchmarkIntPointerMap-8 100000000 24.43 ns/op 0 B/op 0 allocs/op
package main
type mapType interface {
Inc(string) int
Dec(string) int
}
type intPointerMap map[string]*int
func (tqs intPointerMap) Inc(tenant string) int {
ptr, ok := tqs[tenant]
if !ok {
size := 1
tqs[tenant] = &size
return size
}
(*ptr)++
return *ptr
}
func (tqs intPointerMap) Dec(tenant string) int {
ptr, ok := tqs[tenant]
if !ok {
return 0
}
(*ptr)--
if *ptr == 0 {
delete(tqs, tenant)
}
return *ptr
}
type intMap map[string]int
func (tqs intMap) Inc(tenant string) int {
ptr, ok := tqs[tenant]
if !ok {
tqs[tenant] = 1
return 1
}
ptr++
tqs[tenant] = ptr
return ptr
}
func (tqs intMap) Dec(tenant string) int {
ptr, ok := tqs[tenant]
if !ok {
return 0
}
ptr--
if ptr == 0 {
delete(tqs, tenant)
} else {
tqs[tenant] = ptr
}
return ptr
}
package main
import "testing"
func BenchmarkIntMap(b *testing.B) {
m := make(intMap)
benchmarkMap(b, m)
}
func BenchmarkIntPointerMap(b *testing.B) {
m := make(intPointerMap)
benchmarkMap(b, m)
}
func benchmarkMap(b *testing.B, m mapType) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
m.Inc("a")
m.Inc("b")
}
for i := 0; i < b.N; i++ {
m.Dec("b")
m.Dec("a")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment