std::vector<int> elems;
elems.reserve(max_bound_num_of_elems);
// do some push_back()'s
elems.shrink_to_fit();
Is there anything similar in Go? std::vector<int> elems;
elems.reserve(max_bound_num_of_elems);
// do some push_back()'s
elems.shrink_to_fit();
Is there anything similar in Go?“Requests the container to reduce its capacity to fit its size.
“The request is non-binding, and the container implementation is free to optimize otherwise and leave the vector with a capacity greater than its size.
“This may cause a reallocation, but has no effect on the vector size and cannot alter its elements.”
arr := make([]uint64, estimatedLength)
...
arr = arr[:actualLength]If you use make(type, len, capacity), then it would only reallocate if your estimated size was under the actual size.
Also I believe that re-slicing would still use the same underlying array, so it would set the length but still keep the capacity.
You’d have to create a new slice of actual capacity and copy to it.
In the append case, since the underlying slice has capacity, then each append will just extend the length. If estimated length was too small, then reallocation would occur.
In the reslice case, the new slice is a value type that points to the original underlying memory, with a length that is shorter. So no reallocation.
There is a difference in Go’s slices between length and capacity. Length is the number of elements in the slice, and capacity is the number of elements that can fit in the backing array (so len <= cap).