I am trying to understand the actual reasoning behind creating a new dynamic array of double the size of the original array once it gets full as opposed to any reasonably random number (not too small that buffer is getting filled up too often neither it being too large that half the indices are empty).
Apparently, it has to do with performance but can't get my head around it.
For instance:
// original array of size 3 has been allocated which gets filled up at some point
int *arr;
arr = new int[3];
// arr at some point: {1,2,3}
// now there's a request to add a 4 into the array but since arr is full, you delete arr, create a new arr with size 7 instead of 6
newArr: {1,2,3,4,0,0,0}; // assuming you init'd the array to 0
I observe the following:
- you copy the elements from the original array -> O(N)
- you append 4 to the corresponding index -> O(1)
and that's going to be the same if you were say double the array size as well except you'd be reallocating more frequently.
So where's the difference in performance between reallocating double the size vs any reasonably random size?
Edit:
My incomplete understanding:
Sum of power of 2 = Σ2^(N-1)
N=2 -> Σ2^(1) = 2^0 + 2^1 = 1 + 2 = 3 (+1) = 4
Therefore:
1 + 2 + 4 + 8 + ... + Σ2^(N-1) == 3/2 * 2^N ≈ O(N)
And, with M
number of insertions:
O(N) / O(M) = O(1)
Is ny understanding somewhat correct? If so, how would the equation be different for increasing the array size by a constant k
(say 100) factor as opposed to doubling?
ArrayList[T]
uses 1.25x. YARV uses 1.25x. Python uses 1.125x + 3 for smaller x and 1.125x + 6 for large x. 1.5x has some performance advantages over 2x. For a specific definition of "optimal" and an infinitely large array, the optimal value is actually the golden ratio. $\endgroup$