Skip to content

Instantly share code, notes, and snippets.

@shuLhan
Last active January 1, 2016 01:59
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 shuLhan/116e8e526ea20af81f54 to your computer and use it in GitHub Desktop.
Save shuLhan/116e8e526ea20af81f54 to your computer and use it in GitHub Desktop.
package test
import (
"testing"
)
var sum int
func sumByIndex(n int) (sum int) {
sliceint := make([]int, n)
for x := 0; x < n; x++ {
sliceint[x] = x
}
for x := 0; x < n; x++ {
sum += sliceint[x]
}
return sum
}
func sumByElm(n int) (sum int) {
sliceint := make([]int, n)
for x := 0; x < n; x++ {
sliceint[x] = x
}
for _, el := range sliceint {
sum += el
}
return sum
}
func BenchmarkSumByIndex10000(b *testing.B) {
var s int
for x := 0; x < b.N; x++ {
s = sumByIndex(10000)
}
sum = s
b.ReportAllocs()
}
func BenchmarkSumByElm10000(b *testing.B) {
var s int
for x := 0; x < b.N; x++ {
s = sumByElm(10000)
}
sum = s
b.ReportAllocs()
}
func BenchmarkSumByIndex1000000(b *testing.B) {
var s int
for x := 0; x < b.N; x++ {
s = sumByIndex(1000000)
}
sum = s
b.ReportAllocs()
}
func BenchmarkSumByElm1000000(b *testing.B) {
var s int
for x := 0; x < b.N; x++ {
s = sumByElm(1000000)
}
sum = s
b.ReportAllocs()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment