Skip to content

Instantly share code, notes, and snippets.

@karlseguin
Forked from SchumacherFM/bench_test.go
Last active August 29, 2015 14:07
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 karlseguin/14e3b4e4c0f03c10d9da to your computer and use it in GitHub Desktop.
Save karlseguin/14e3b4e4c0f03c10d9da to your computer and use it in GitHub Desktop.
package main
// @see https://twitter.com/karlseguin/status/524452778093977600
import (
"math/rand"
"strconv"
"testing"
)
const (
SIZE = 5000
LOOKUPS = 10
)
func BenchmarkStringMap(b *testing.B) {
lookup := make(map[string]string, SIZE)
for i := 0; i < SIZE; i += 1 {
k := strconv.Itoa(i) // FYI: converts int to string
lookup[k] = "value"
}
rand.Seed(int64(b.N))
b.ResetTimer()
for n := 0; n < b.N; n++ {
for i := 0; i < LOOKUPS; i++ {
needle := strconv.Itoa(rand.Intn(SIZE))
if _, ok := lookup[needle]; ok {
}
}
}
}
func BenchmarkStringSlice(b *testing.B) {
lookup := make([]string, SIZE*2)
for i := 0; i < SIZE; i += 2 {
lookup[i] = strconv.Itoa(i / 2)
lookup[i+1] = "value"
}
rand.Seed(int64(b.N))
b.ResetTimer()
for n := 0; n < b.N; n++ {
for i := 0; i < LOOKUPS; i++ {
needle := strconv.Itoa(rand.Intn(SIZE))
for j := 0; j < SIZE; j += 2 {
if lookup[j] == needle {
}
}
}
}
}
func BenchmarkStringArrays(b *testing.B) {
lookup := [SIZE * 2]string{}
for i := 0; i < SIZE; i += 2 {
lookup[i] = strconv.Itoa(i / 2)
lookup[i+1] = "value"
}
rand.Seed(int64(b.N))
b.ResetTimer()
for i := 0; i < b.N; i++ {
for i := 0; i < LOOKUPS; i++ {
needle := strconv.Itoa(rand.Intn(SIZE))
for j := 0; j < SIZE; j += 2 {
if lookup[j] == needle {
}
}
}
}
}
func BenchmarkStructSlice(b *testing.B) {
lookup := make([]struct{ key, value string }, SIZE)
for i := 0; i < SIZE; i++ {
lookup[i].key = strconv.Itoa(i)
lookup[i].value = "value"
}
rand.Seed(int64(b.N))
b.ResetTimer()
for n := 0; n < b.N; n++ {
for i := 0; i < LOOKUPS; i++ {
needle := strconv.Itoa(rand.Intn(SIZE))
for j := 0; j < SIZE; j++ {
if lookup[j].key == needle {
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment