Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save twpayne/f7146a8ba28b7e0b9cd830de6a9db51a to your computer and use it in GitHub Desktop.
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++ {
a := make([]int, 0, n)
for j := 0; j < n; j += 2 {
a = appendFuncVargs(a, i, i+1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment