Hi G4143, how are you?
I have created a file with following script “sliceBenchmark.go”:
package main
const SLICE_CAPACITY = 8
func main() {
fixedArray()
withCapacity()
withoutCapacity()
}
func fixedArray() {
var slc [SLICE_CAPACITY]uint
for i := 0; i < SLICE_CAPACITY; i++ {
slc[i] = 6
}
}
func withCapacity() {
slc := make([]uint, 0, SLICE_CAPACITY)
for i := 0; i < SLICE_CAPACITY; i++ {
slc = append(slc, 6)
}
}
func withoutCapacity() {
slc := []uint{}
for i := 0; i < SLICE_CAPACITY; i++ {
slc = append(slc, 6)
}
}
And another file with benchmarks “sliceBenchmark_test.go”:
package main
import (
"testing"
)
func BenchmarkWithCapacity(b *testing.B) {
for n := 0; n < b.N; n++ {
withCapacity()
}
}
func BenchmarkWithoutCapacity(b *testing.B) {
for n := 0; n < b.N; n++ {
withoutCapacity()
}
}
func BenchmarkFixedArray(b *testing.B) {
for n := 0; n < b.N; n++ {
fixedArray()
}
}
With my laptop, I have got the following results:
|BenchmarkWithCapacity-4 |210583917| 5.995 ns/op|
|BenchmarkWithoutCapacity-4 |10043202| 113.6 ns/op|
|BenchmarkFixedArray-4 |381437634| 3.104 ns/op|
The function with capacity is 20 times faster than without capacity.
And fixed array is faster than the slice with capacity