Skip to content

Instantly share code, notes, and snippets.

@scrouthtv
Created October 13, 2021 09:24
Show Gist options
  • Save scrouthtv/73f1bc9494d37593e91f148b2a207191 to your computer and use it in GitHub Desktop.
Save scrouthtv/73f1bc9494d37593e91f148b2a207191 to your computer and use it in GitHub Desktop.
Go append vs prepend
package app
import "testing"
import "math/rand"
func BenchmarkAppend(b *testing.B) {
arr := make([]int, 5)
for i, _ := range arr {
arr[i] = rand.Int()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = append(arr, 5)
}
}
func BenchmarkPrepend(b *testing.B) {
arr := make([]int, 5)
for i, _ := range arr {
arr[i] = rand.Int()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = append([]int{5}, arr...)
}
}
@scrouthtv
Copy link
Author

I used this to compare the performance of adding a single item

  • to the end of a slice
  • at the beginning of a slice

Output on my machine:

 ~  go test -bench . -benchmem -count 3 -v
goos: linux
goarch: amd64
pkg: app
cpu: Intel(R) Core(TM) i5-3570 CPU @ 3.40GHz
BenchmarkAppend
BenchmarkAppend-4    	19150089	        68.33 ns/op	      80 B/op	       1 allocs/op
BenchmarkAppend-4    	20065119	        63.99 ns/op	      80 B/op	       1 allocs/op
BenchmarkAppend-4    	17504325	        59.39 ns/op	      80 B/op	       1 allocs/op
BenchmarkPrepend
BenchmarkPrepend-4   	23012112	        48.21 ns/op	      48 B/op	       1 allocs/op
BenchmarkPrepend-4   	24711933	        48.14 ns/op	      48 B/op	       1 allocs/op
BenchmarkPrepend-4   	25021759	        48.13 ns/op	      48 B/op	       1 allocs/op
PASS
ok  	app	7.512s

Surprisingly, prepending is faster than appending.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment