Skip to content

Instantly share code, notes, and snippets.

@collinvandyck
Last active October 1, 2017 18:29
Show Gist options
  • Save collinvandyck/1b4ca991eb07646895711548f267e0ef to your computer and use it in GitHub Desktop.
Save collinvandyck/1b4ca991eb07646895711548f267e0ef to your computer and use it in GitHub Desktop.
package main
import (
"math/rand"
"testing"
)
type mapType map[int64]struct{}
type sliceType []int64
type finder interface {
find(int64) bool
}
func (s sliceType) find(num int64) bool {
for i := 0; i < len(s); i++ {
if s[i] == num {
return true
}
}
return false
}
func (m mapType) find(num int64) bool {
_, ok := m[num]
return ok
}
func makeSlice(size int) sliceType {
s := make(sliceType, size)
for i := 0; i < size; i++ {
s[i] = rand.Int63()
}
return s
}
func makeMap(size int) mapType {
m := make(mapType)
for i := 0; i < size; i++ {
r := rand.Int63()
m[r] = struct{}{}
}
return m
}
func benchFind(t *testing.B, finder finder) {
t.ResetTimer()
for i := 0; i < t.N; i++ {
_ = finder.find(rand.Int63())
}
}
func benchMap(size int, t *testing.B) {
benchFind(t, makeMap(size))
}
func benchSlice(size int, t *testing.B) {
benchFind(t, makeSlice(size))
}
func BenchmarkMaps4(t *testing.B) {
benchMap(4, t)
}
func BenchmarkSlice4(t *testing.B) {
benchSlice(4, t)
}
func BenchmarkMaps8(t *testing.B) {
benchMap(8, t)
}
func BenchmarkSlice8(t *testing.B) {
benchSlice(8, t)
}
func BenchmarkMaps16(t *testing.B) {
benchMap(16, t)
}
func BenchmarkSlice16(t *testing.B) {
benchSlice(16, t)
}
func BenchmarkMaps32(t *testing.B) {
benchMap(32, t)
}
func BenchmarkSlice32(t *testing.B) {
benchSlice(32, t)
}
func BenchmarkMaps64(t *testing.B) {
benchMap(64, t)
}
func BenchmarkSlice64(t *testing.B) {
benchSlice(64, t)
}
func BenchmarkMaps128(t *testing.B) {
benchMap(128, t)
}
func BenchmarkSlice128(t *testing.B) {
benchSlice(128, t)
}
func BenchmarkMaps256(t *testing.B) {
benchMap(256, t)
}
func BenchmarkSlice256(t *testing.B) {
benchSlice(256, t)
}
// RESULTS:
$ go test maps_and_slices_test.go -bench .
goos: darwin
goarch: amd64
BenchmarkMaps4-8 50000000 32.2 ns/op
BenchmarkSlice4-8 50000000 27.4 ns/op
BenchmarkMaps8-8 50000000 30.8 ns/op
BenchmarkSlice8-8 50000000 28.7 ns/op
BenchmarkMaps16-8 50000000 35.1 ns/op
BenchmarkSlice16-8 50000000 30.4 ns/op
BenchmarkMaps32-8 50000000 35.4 ns/op
BenchmarkSlice32-8 30000000 35.9 ns/op
BenchmarkMaps64-8 50000000 34.6 ns/op
BenchmarkSlice64-8 30000000 50.2 ns/op
BenchmarkMaps128-8 50000000 36.0 ns/op
BenchmarkSlice128-8 20000000 83.5 ns/op
BenchmarkMaps256-8 30000000 35.2 ns/op
BenchmarkSlice256-8 10000000 123 ns/op
PASS
ok command-line-arguments 21.756s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment