Skip to content

Instantly share code, notes, and snippets.

@agocs
Created May 18, 2016 18:08
Show Gist options
  • Save agocs/3237f27a0ce93ec653495fdcaf654c24 to your computer and use it in GitHub Desktop.
Save agocs/3237f27a0ce93ec653495fdcaf654c24 to your computer and use it in GitHub Desktop.
Is it faster to append, or to just assign in place?
package main
var sliceOf20Ints = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
func toIfaceWithAppend(ints []int) []interface{} {
var ifaceInts = make([]interface{}, 0, len(ints))
for _, someInt := range ints {
ifaceInts = append(ifaceInts, someInt)
}
return ifaceInts
}
func toIfaceInPlace(ints []int) []interface{} {
var ifaceInts = make([]interface{}, len(ints))
for i, someInt := range ints {
ifaceInts[i] = someInt
}
return ifaceInts
}
Christophers-MacBook-Pro:tmp cagocs$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkAppend-8 2000000 710 ns/op
BenchmarkInPlace-8 2000000 718 ns/op
ok github.com/agocs/tmp 4.306s
Christophers-MacBook-Pro:tmp cagocs$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkAppend-8 2000000 717 ns/op
BenchmarkInPlace-8 2000000 704 ns/op
ok github.com/agocs/tmp 4.291s
Christophers-MacBook-Pro:tmp cagocs$
package main
import "testing"
func BenchmarkAppend(b *testing.B) {
for n := 0; n < b.N; n++ {
toIfaceWithAppend(sliceOf20Ints)
}
}
func BenchmarkInPlace(b *testing.B) {
for n := 0; n < b.N; n++ {
toIfaceInPlace(sliceOf20Ints)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment