Compare and benchmark 3 kinds of slice append |
|
package main |
|
const length = 1000 |
|
1) |
func genByAppend() []int { var s []int for i := 0; i < length; i++ { s = append(s, i) } return s } |
2) |
func genByAppendCap() []int { s := make([]int, 0, length) for i := 0; i < length; i++ { s = append(s, i) } |
return s } |
|
3) |
func genByAssign() []int { s := make([]int, length) for i := 0; i < length; i++ { s[i] = i } return s } |
$ go test -v -bench=.
|
|
goos: darwin goarch: arm64 pkg: github.com/hhow09/gobyexample/examples/performance-slice-append BenchmarkGenByAppend BenchmarkGenByAppend-8 563953 2148 ns/op BenchmarkGenByAppendCap BenchmarkGenByAppendCap-8 2595301 455.5 ns/op BenchmarkGenByAssign BenchmarkGenByAssign-8 4048084 294.9 ns/op PASS ok github.com/hhow09/gobyexample/examples/performance-slice-append 5.483s |
Next example: Select.