Skip to content

Instantly share code, notes, and snippets.

@SkYNewZ
Created January 25, 2022 15:29
Show Gist options
  • Save SkYNewZ/ebdcb5d1737bcabc66238d0818250f4b to your computer and use it in GitHub Desktop.
Save SkYNewZ/ebdcb5d1737bcabc66238d0818250f4b to your computer and use it in GitHub Desktop.
Golang append using make/cap vs slice literal
❯ go test -bench=. -v ./main_test.go
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
BenchmarkAppendMake
BenchmarkAppendMake-8 17486152 67.63 ns/op 0 B/op 0 allocs/op
BenchmarkAppendMakeCap
BenchmarkAppendMakeCap-8 2189421 540.8 ns/op 2040 B/op 8 allocs/op
PASS
ok command-line-arguments 3.124s
package main
import (
"testing"
)
func BenchmarkAppendMake(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
v := make([]int, 0, 100)
for i := 0; i < 100; i++ {
v = append(v, i)
}
}
}
func BenchmarkAppendMakeCap(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var v []int
for i := 0; i < 100; i++ {
v = append(v, i)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment