Skip to content

Instantly share code, notes, and snippets.

@ndyakov
Created March 8, 2015 14:00
Show Gist options
  • Save ndyakov/9feaf9f89baa38ec2c36 to your computer and use it in GitHub Desktop.
Save ndyakov/9feaf9f89baa38ec2c36 to your computer and use it in GitHub Desktop.
benchmark prepend golang
package main
import "testing"
func BenchmarkPrependAppend(b *testing.B) {
s := []string{"one", "two", "three", "four"}
word := "zero"
for i := 0; i < b.N; i++ {
s = append([]string{word}, s...)
}
}
func BenchmarkPrependCopy(b *testing.B) {
s := []string{"one", "two", "three", "four"}
word := "zero"
for i := 0; i < b.N; i++ {
s = append(s, "")
copy(s[1:], s)
s[0] = word
}
}
func BenchmarkPrependMake(b *testing.B) {
s := []string{"one", "two", "three", "four"}
word := "zero"
for i := 0; i < b.N; i++ {
res := make([]string, len(s)+1)
res[0] = word
copy(res[1:], s)
s = res
}
}
BenchmarkPrependAppend 20000 165476 ns/op 163872 B/op 2 allocs/op
BenchmarkPrependCopy 200000 170145 ns/op 91 B/op 0 allocs/op
BenchmarkPrependMake 20000 161054 ns/op 163856 B/op 1 allocs/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment