Skip to content

Instantly share code, notes, and snippets.

@lu4p
Created Dec 2, 2020
Embed
What would you like to do?
golang append only vs make
package main
func plainAppend(elms int) {
var foo []int
for i := 0; i < elms; i++ {
foo = append(foo, i)
}
}
func withMake(elms int) {
foo := make([]int, 0, elms)
for i := 0; i < elms; i++ {
foo = append(foo, i)
}
}
package main
import "testing"
func Benchmark10(b *testing.B) {
const elmCount = 10
// iterations are controlled via -benchtime=Nx
b.Run("append", func(b *testing.B) {
for i := 0; i < b.N; i++ {
plainAppend(elmCount)
}
})
b.Run("with make", func(b *testing.B) {
for i := 0; i < b.N; i++ {
withMake(elmCount)
}
})
}
func Benchmark100(b *testing.B) {
const elmCount = 100
// iterations are controlled via -benchtime=Nx
b.Run("append", func(b *testing.B) {
for i := 0; i < b.N; i++ {
plainAppend(elmCount)
}
})
b.Run("with make", func(b *testing.B) {
for i := 0; i < b.N; i++ {
withMake(elmCount)
}
})
}
func Benchmark1k(b *testing.B) {
const elmCount = 1000
// iterations are controlled via -benchtime=Nx
b.Run("append", func(b *testing.B) {
for i := 0; i < b.N; i++ {
plainAppend(elmCount)
}
})
b.Run("with make", func(b *testing.B) {
for i := 0; i < b.N; i++ {
withMake(elmCount)
}
})
}
func Benchmark10k(b *testing.B) {
const elmCount = 10000
// iterations are controlled via -benchtime=Nx
b.Run("append", func(b *testing.B) {
for i := 0; i < b.N; i++ {
plainAppend(elmCount)
}
})
b.Run("with make", func(b *testing.B) {
for i := 0; i < b.N; i++ {
withMake(elmCount)
}
})
}
func Benchmark100k(b *testing.B) {
const elmCount = 100_000
// iterations are controlled via -benchtime=Nx
b.Run("append", func(b *testing.B) {
for i := 0; i < b.N; i++ {
plainAppend(elmCount)
}
})
b.Run("with make", func(b *testing.B) {
for i := 0; i < b.N; i++ {
withMake(elmCount)
}
})
}
func Benchmark1Million(b *testing.B) {
const elmCount = 1000 * 1000
// iterations are controlled via -benchtime=Nx
b.Run("append", func(b *testing.B) {
for i := 0; i < b.N; i++ {
plainAppend(elmCount)
}
})
b.Run("with make", func(b *testing.B) {
for i := 0; i < b.N; i++ {
withMake(elmCount)
}
})
}
$ go test -bench=. -count=10 -benchtime=100x > bench.out
# https://godoc.org/golang.org/x/perf/cmd/benchstat
$ benchstat bench.out
name time/op
10/append-8 729ns ±62%
10/with_make-8 119ns ±84%
100/append-8 1.46µs ±84%
100/with_make-8 454ns ±99%
1k/append-8 5.28µs ±33%
1k/with_make-8 2.61µs ±54%
10k/append-8 111µs ±23%
10k/with_make-8 31.4µs ±11%
100k/append-8 1.16ms ± 8%
100k/with_make-8 248µs ±11%
1Million/append-8 8.57ms ± 3%
1Million/with_make-8 2.83ms ± 1%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment