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
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) | |
} | |
} |