Skip to content

Instantly share code, notes, and snippets.

@fujiwara
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fujiwara/9fc5d1601f24b29f1e3e to your computer and use it in GitHub Desktop.
Save fujiwara/9fc5d1601f24b29f1e3e to your computer and use it in GitHub Desktop.
package mapbench_test
import "testing"
var N = 1000000
func BenchmarkMap(b *testing.B) {
for i := 0; i < b.N; i++ {
m := map[int]int{}
for j := 0; j < N; j++ {
m[j] = j
}
}
}
func BenchmarkMapCap(b *testing.B) {
for i := 0; i < b.N; i++ {
m := make(map[int]int, N)
for j := 0; j < N; j++ {
m[j] = j
}
}
}
func BenchmarkMapLookup(b *testing.B) {
m := map[int]int{}
for j := 0; j < N; j++ {
m[j] = j
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < N; j++ {
_, _ = m[i]
}
}
}
func BenchmarkMapCapLookup(b *testing.B) {
m := make(map[int]int, N)
for j := 0; j < N; j++ {
m[j] = j
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < N; j++ {
_, _ = m[i]
}
}
}
$ go test mapbench_test.go -bench . -benchmem
testing: warning: no tests to run
PASS
BenchmarkMap 5 310879905 ns/op 84001936 B/op 59035 allocs/op
BenchmarkMapCap 10 185929105 ns/op 38369164 B/op 4310 allocs/op
BenchmarkMapLookup 100 12966770 ns/op 0 B/op 0 allocs/op
BenchmarkMapCapLookup 100 13090509 ns/op 0 B/op 0 allocs/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment