Golang Slice
there are three way to declare a slice in golang.
define slice
// use slice literal
var slice []int
// use make without cap
var slice = make([]int, 10) // len == cap = 10
// use make with cap
var slice = make([]int, 0, 10) // len=0. cap = 10
// The append preformence compare
// slice literal
func AppendToNOMakeSlice(count int32) {
var slice []int32
var idx int32 = 0
for ; idx < count; idx++ {
slice = append(slice, idx)
}
}
Bench mark
const numOfItems int32 = 1000000
func BenchmarkAppendToNOMakeSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
AppendToNOMakeSlice(numOfItems)
}
}
// bench result
/*goos: darwin
goarch: amd64
BenchmarkAppendToNOMakeSlice-8 100 12910359 ns/op
*/
make without cap
func AppendToMakeSlice(count int32) {
var slice = make([]int32, count)
var idx int32 = 0
for ; idx < count; idx++ {
slice[idx] = idx
}
}
func BenchmarkAppendToMakeSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
AppendToMakeSlice(numOfItems)
}
}
bench result
go test -v -bench=BenchmarkAppendToMakeSlice
goos: darwin
goarch: amd64
pkg: github.com/xxxx/go-common/bench
BenchmarkAppendToMakeSlice-8 474 2160812 ns/op
Make slice with cap
func AppendToMakeSliceWithCap(count int32) {
var slice = make([]int32, 0, count)
var idx int32 = 0
for ; idx < count; idx++ {
slice = append(slice, idx)
}
}
/*
goos: darwin
goarch: amd64
BenchmarkAppendToCapSlice
BenchmarkAppendToCapSlice-8 388 2699622 ns/op
*/
func BenchmarkAppendToCapSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
AppendToMakeSliceWithCap(numOfItems)
}
}
Summary
- Literal slice define is not effective when append large amount of elements
- Slice declared with make is more efficient than literal declared.