Array vs Slice — Go Benchmark
Compare fixed-size arrays, pre-allocated slices, and dynamically grown slices.
Compares three ways to store a sequence of integers in Go: a fixed-size array, a slice pre-allocated with make, and a slice grown dynamically via append. The array and pre-allocated slice are written to by index, while the dynamic slice starts empty each iteration and grows through repeated appends. This highlights the cost of slice growth and bounds-checking relative to compile-time-fixed arrays.
1 CPU
Fastest
ArraySlowest
Dynamic Slice32 CPUs
Fastest
ArraySlowest
Dynamic SliceArray
FastestA fixed-size [1000]int array allocated on the stack. Each iteration writes to every index. Because the size is known at compile time, the compiler can elide bounds checks and the data stays contiguous in a single stack frame with zero heap allocations.
Preallocated Slice
Uses make([]int, 1000) to allocate the full backing array once before the benchmark loop. Each iteration writes to every index, similar to the array benchmark. The slice header adds a small overhead compared to a raw array, but avoids all growth-related allocations.
Dynamic Slice
SlowestStarts with a nil slice and grows it via append on every element. Each time the underlying array runs out of capacity, the runtime allocates a larger backing array and copies existing elements over. This represents the worst case when the final size is unknown upfront.
Contributors