Skip to content

Instantly share code, notes, and snippets.

@nirui
Created April 30, 2018 00:12
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 nirui/3cd8ddcb1fbd3f0ad43b79b4ee161280 to your computer and use it in GitHub Desktop.
Save nirui/3cd8ddcb1fbd3f0ad43b79b4ee161280 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/rand"
"testing"
)
var sample = makeSample()
const sampleSize = 4096
func makeSample() []byte {
s := make([]byte, sampleSize)
rand.Read(s)
return s
}
func BenchmarkRangeIndex(b *testing.B) {
var result uint64
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for ss := range sample {
result += uint64(sample[ss])
}
}
}
func BenchmarkRangeValue(b *testing.B) {
var result uint64
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, ss := range sample {
result += uint64(ss)
}
}
}
func BenchmarkIndex(b *testing.B) {
var result uint64
sLen := len(sample)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for s := 0; s < sLen; s++ {
result += uint64(sample[s])
}
}
}
@nirui
Copy link
Author

nirui commented Apr 30, 2018

Benchmark Exec/Sec Cost/Exec Allocated/Op Allocations/Op
BenchmarkRangeIndex-2 1000000 1887 ns/op 0 B/op 0 allocs/op
BenchmarkRangeValue-2 1000000 1851 ns/op 0 B/op 0 allocs/op
BenchmarkIndex-2 500000 3673 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