Created
October 18, 2019 10:38
-
-
Save mackee/10a6b89cb418d57251e5a57fb0720c89 to your computer and use it in GitHub Desktop.
Map performance degradation of key length
This file contains 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 ( | |
"bytes" | |
"math/rand" | |
"testing" | |
) | |
func genKey(n int) string { | |
ss := &bytes.Buffer{} | |
for i := 0; i < n; i++ { | |
ss.WriteRune(rune(rand.Intn(93) + 33)) | |
} | |
return ss.String() | |
} | |
func BenchmarkMapKeyLength_1(b *testing.B) { benchmarkMap(b, 1) } | |
func BenchmarkMapKeyLength_5(b *testing.B) { benchmarkMap(b, 5) } | |
func BenchmarkMapKeyLength_10(b *testing.B) { benchmarkMap(b, 10) } | |
func BenchmarkMapKeyLength_20(b *testing.B) { benchmarkMap(b, 20) } | |
func BenchmarkMapKeyLength_50(b *testing.B) { benchmarkMap(b, 50) } | |
func BenchmarkMapKeyLength_100(b *testing.B) { benchmarkMap(b, 100) } | |
func BenchmarkMapKeyLength_500(b *testing.B) { benchmarkMap(b, 500) } | |
func BenchmarkMapKeyLength_1000(b *testing.B) { benchmarkMap(b, 1000) } | |
func benchmarkMap(b *testing.B, l int) { | |
keys := make([]string, 0, b.N) | |
for i := 0; i < b.N; i++ { | |
keys = append(keys, genKey(l)) | |
} | |
m := make(map[string]struct{}, b.N) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
m[keys[i]] = struct{}{} | |
} | |
for i := 0; i < b.N; i++ { | |
a, b := keys[rand.Intn(b.N)], keys[rand.Intn(b.N)] | |
m[a], m[b] = m[b], m[a] | |
} | |
} |
This file contains 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
$ go test -v -bench . | |
goos: darwin | |
goarch: amd64 | |
pkg: github.com/mackee/sandbox/gostudy-map-benchmark | |
BenchmarkMapKeyLength_1-8 5959239 216 ns/op | |
BenchmarkMapKeyLength_5-8 3397646 709 ns/op | |
BenchmarkMapKeyLength_10-8 2078060 602 ns/op | |
BenchmarkMapKeyLength_20-8 1972189 629 ns/op | |
BenchmarkMapKeyLength_50-8 1816406 673 ns/op | |
BenchmarkMapKeyLength_100-8 1711934 745 ns/op | |
BenchmarkMapKeyLength_500-8 1298208 1028 ns/op | |
BenchmarkMapKeyLength_1000-8 1000000 1170 ns/op | |
PASS | |
ok github.com/mackee/sandbox/gostudy-map-benchmark 93.767s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment