Skip to content

Instantly share code, notes, and snippets.

@twpayne
Last active June 14, 2016 20:58
Show Gist options
  • Select an option

  • Save twpayne/a29bf1e6ef268e008eea7fd0cc8b1204 to your computer and use it in GitHub Desktop.

Select an option

Save twpayne/a29bf1e6ef268e008eea7fd0cc8b1204 to your computer and use it in GitHub Desktop.
Golang benchmark test
package argbench
import (
"testing"
)
// n limits the size of the constructed arrays, to prevent the benchmarks from
// measuring memory bandwidth instead of performance.
const n = 1024
func BenchmarkAppendInline(b *testing.B) {
for i := 0; i < b.N; i++ {
a := make([]int, 0, n)
for j := 0; j < n; j++ {
a = append(a, i)
}
}
}
func appendFunc(a []int, i int) []int {
return append(a, i)
}
func BenchmarkAppendCall(b *testing.B) {
for i := 0; i < b.N; i++ {
a := make([]int, 0, n)
for j := 0; j < n; j++ {
a = appendFunc(a, i)
}
}
}
func appendFuncVargs(a []int, is ...int) []int {
return append(a, is...)
}
func BenchmarkAppendCallVargs(b *testing.B) {
for i := 0; i < b.N; i++ {
a := make([]int, 0, n)
for j := 0; j < n; j++ {
a = appendFuncVargs(a, i)
}
}
}
func BenchmarkAppendCallVargs2(b *testing.B) {
for i := 0; i < b.N; i += 2 {
a := make([]int, 0, n)
for j := 0; j < n; j++ {
a = appendFuncVargs(a, i, i+1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment