Why you need to avoid using append in Go

func WithAppend() []string {
var l []string
for i := 0; i < 100; i++ {
l = append(l, "x")
}

return l
}
func WithAssignAlloc() []string {
l := make([]string, 100)
for i := 0; i < 100; i++ {
l[i] = "x"
}

return l
}
func BenchmarkWithAppend(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
WithAppend()
}
}
func BenchmarkWithAssignAlloc(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
WithAssignAlloc()
}
}
BenchmarkWithAppend
BenchmarkWithAppend-8 863949 1322 ns/op 4080 B/op 8 allocs/op
BenchmarkWithAssignAlloc
BenchmarkWithAssignAlloc-8 2343424 523 ns/op 1792 B/op 1 allocs/op
func WithAppendAlloc() []string {
l := make([]string, 0, 100)
for i := 0; i < 100; i++ {
l = append(l, "x")
}
return l
}
BenchmarkWithAppend
BenchmarkWithAppend-8 863949 1322 ns/op 4080 B/op 8 allocs/op
BenchmarkWithAppendAlloc
BenchmarkWithAppendAlloc-8 2543119 514 ns/op 1792 B/op 1 allocs/op
BenchmarkWithAssignAlloc
BenchmarkWithAssignAlloc-8 2343424 523 ns/op 1792 B/op 1 allocs/op

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store