Performance Evaluation: Slicing and Dicing with and without Capacity Hints
In Go, the make function is used to create slices, maps, and channels with a specified capacity. When initialising slices with make, providing a capacity hint can be beneficial for performance, especially when you know the approximate size of the data.
// Creating a slice with a capacity hint of 10
mySlice := make([]int, 0, 10)
Unlike maps, slice capacity is not a hint: the compiler will allocate enough memory for the capacity of the slice as provided to make(), which means that subsequent append() operations will incur zero allocations (until the length of the slice matches the capacity, after which any appends will require a resize to hold additional elements).
Example
package awesomeProject2
import (
"testing"
)
// BenchmarkBadCapacityHint benchmarks appending to a slice without a good capacity hint.
func BenchmarkBadCapacityHint(b *testing.B) {
for i := 0; i < b.N; i++ {
var badSlice []int
for j := 0; j < 1000; j++ {
badSlice = append(badSlice, j)
}
}
}
// BenchmarkGoodCapacityHint benchmarks appending to a slice with a good capacity hint.
func BenchmarkGoodCapacityHint(b *testing.B) {
for i := 0; i < b.N; i++ {
goodSlice := make([]int, 0, 1000)
for j := 0; j < 1000; j++ {
goodSlice = append(goodSlice, j)
}
}
}
Output:
We can clearly see the difference between passing the capacity while creating slice and vice versa.
GoLang developer | Node.js developer | Backend developer
1 年Thank you na