Last active
December 20, 2021 11:37
-
-
Save stokito/d3a8e26f50c7839b82bd36a4df356e0e to your computer and use it in GitHub Desktop.
GoLang bytes slice as a key map. Just convert the slice to string and Go will optimize it https://stackoverflow.com/questions/20297503/slice-as-a-key-in-map https://github.com/golang/go/wiki/CompilerOptimizations#string-and-byte
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 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 | |
} |
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 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found the optimization golang/go#3512