Boosting Go Performance: Dynamic vs Static Allocation
A simple test about the performance of dynamic and static allocation in Go to create a new slice
In Go, there are two primary methods of allocating a new slice: using the make function to pre-allocate the slice and set each value, or creating an empty slice and appending new elements to it.
While both approaches produce the same result, their performance differs significantly due to the underlying operations within these functions.
In this article, we will test the performance of dynamic and static allocation in Go, exploring which method is more efficient and why.
Static and dynamic allocation
In static allocation, the memory is allocated once and accessed directly, without allocating additional memory for the elements. This solution will only work if you know the number of elements in advance.
With dynamic allocation, instead, it is possible to create an empty slice without specifying the dimension, and then add new values at the end using the append function.
We can now look at the code:
// Number of elements to create
n := 1000
// Case 1: append approach (dynamic)
var arr1 []int
for i := 0…