Skip to content

Instantly share code, notes, and snippets.

@rogpeppe
Created March 17, 2011 08:37
Show Gist options
  • Save rogpeppe/874010 to your computer and use it in GitHub Desktop.
Save rogpeppe/874010 to your computer and use it in GitHub Desktop.
go map/slice/array benchmark
package main
import (
"fmt"
"testing"
)
const Size = 1e6
var (
array [Size]int
slice = make([]int, Size)
Map = make(map[int]int)
r int // to avoid the compiler optimising away the access
)
func init() {
for i, _ := range array {
array[i] = i
slice[i] = i
Map[i] = i
}
}
func main() {
fmt.Printf("array %v\n", testing.Benchmark(BenchmarkArrayAccess))
fmt.Printf("slice %v\n", testing.Benchmark(BenchmarkSliceAccess))
fmt.Printf("map %v\n", testing.Benchmark(BenchmarkMapAccess))
fmt.Printf("array range %v\n", testing.Benchmark(BenchmarkArrayRangeAccess))
fmt.Printf("array slice range %v\n", testing.Benchmark(BenchmarkArraySliceRangeAccess))
fmt.Printf("slice range %v\n", testing.Benchmark(BenchmarkSliceRangeAccess))
fmt.Printf("map range %v\n", testing.Benchmark(BenchmarkMapRangeAccess))
}
func BenchmarkArrayAccess(b *testing.B) {
for i := b.N-1; i >= 0; i-- {
k := 0
for j := Size-1; j >= 0; j-- {
k += array[j]
}
r = k
}
}
func BenchmarkArrayRangeAccess(b *testing.B) {
for i := b.N-1; i >= 0; i-- {
k := 0
for _, x := range array {
k += x
}
r = k
}
}
func BenchmarkArraySliceRangeAccess(b *testing.B) {
for i := b.N-1; i >= 0; i-- {
k := 0
for _, x := range array[:] {
k += x
}
r = k
}
}
func BenchmarkSliceRangeAccess(b *testing.B) {
a := slice
for i := b.N-1; i >= 0; i-- {
k := 0
for _, x := range a {
k += x
}
r = k
}
}
func BenchmarkSliceAccess(b *testing.B) {
a := slice
for i := b.N-1; i >= 0; i-- {
k := 0
for j := Size-1; j >= 0; j-- {
k += a[j]
}
r = k
}
}
func BenchmarkMapRangeAccess(b *testing.B) {
a := Map
for i := b.N-1; i >= 0; i-- {
k := 0
for _, x := range a {
k += x
}
r = k
}
}
func BenchmarkMapAccess(b *testing.B) {
a := Map
for i := b.N-1; i >= 0; i-- {
k := 0
for j := Size-1; j >= 0; j-- {
k += a[j]
}
r = k
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment