Skip to content

Instantly share code, notes, and snippets.

@stokito
Last active December 20, 2021 11:37
Show Gist options
  • Save stokito/d3a8e26f50c7839b82bd36a4df356e0e to your computer and use it in GitHub Desktop.
Save stokito/d3a8e26f50c7839b82bd36a4df356e0e to your computer and use it in GitHub Desktop.
package bytesmap
var m = make(map[string]*string)
// this works faster
func GetOrDefaultInline(host []byte) *string {
hc, found := m[string(host)]
if !found {
m[string(host)] = nil
}
return hc
}
func GetOrDefault(host []byte) *string {
hostStr := string(host) // convert bytes to str only once
hc, found := m[hostStr]
if !found {
m[hostStr] = nil
}
return hc
}
package bytesmap
import (
"testing"
)
var host1 = []byte("host1")
var host2 = []byte("host2")
var host3 = []byte("host3")
func TestGetOrDefault(t *testing.T) {
// FAILED: expected 0 allocations, got 6.000000
n := testing.AllocsPerRun(100, func() {
GetOrDefault(host1)
GetOrDefault(host1)
GetOrDefault(host2)
GetOrDefault(host2)
GetOrDefault(host3)
GetOrDefault(host3)
})
if n != 0 {
t.Fatalf("expected 0 allocations, got %f", n)
}
}
// Zero allocations i.e. no any garbage
func TestGetOrDefaultInline(t *testing.T) {
n := testing.AllocsPerRun(100, func() {
GetOrDefaultInline(host1)
GetOrDefaultInline(host1)
GetOrDefaultInline(host2)
GetOrDefaultInline(host2)
GetOrDefaultInline(host3)
GetOrDefaultInline(host3)
})
if n != 0 {
t.Fatalf("expected 0 allocations, got %f", n)
}
}
@stokito
Copy link
Author

stokito commented Nov 8, 2021

Found the optimization golang/go#3512

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