Skip to content

Instantly share code, notes, and snippets.

@msmith
Created November 18, 2019 16:36
Show Gist options
  • Save msmith/01ef66457a525fe316f5ac5128e27059 to your computer and use it in GitHub Desktop.
Save msmith/01ef66457a525fe316f5ac5128e27059 to your computer and use it in GitHub Desktop.
Append with preallocated capacity

Benchmarking result

$ go test -bench=.
goos: darwin
goarch: amd64
BenchmarkGrowZero-12            	 3067180	       383 ns/op
BenchmarkGrowPreallocated-12    	 7515637	       158 ns/op
PASS
ok  	_/Users/msmith/Desktop/test-alloc	4.059s
package main
import "fmt"
func main() {
GrowZero(true)
GrowPreallocated(true)
}
func GrowZero(debug bool) {
var a []int
about(debug, a)
for i := 0; i < 33; i++ {
a = append(a, i)
about(debug, a)
}
}
func GrowPreallocated(debug bool) {
a := make([]int, 0, 40)
about(debug, a)
for i := 0; i < 33; i++ {
a = append(a, i)
about(debug, a)
}
}
func about(debug bool, a []int) {
if debug {
fmt.Printf("len=%d cap=%d %v\n", len(a), cap(a), a)
}
}
package main
import "testing"
func BenchmarkGrowZero(b *testing.B) {
// run the Fib function b.N times
for n := 0; n < b.N; n++ {
GrowZero(false)
}
}
func BenchmarkGrowPreallocated(b *testing.B) {
// run the Fib function b.N times
for n := 0; n < b.N; n++ {
GrowPreallocated(false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment