patternMinor
Why is it most efficient to resize a dynamic array to 2 * array.length()?
Viewed 0 times
whyresizearraylengthefficientdynamicmost
Problem
By dynamic array, I mean an array that when it becomes full we replace it with a new array having greater capacity than the previous array.
I read in a textbook that doubling the size of the array is the most efficient resizing. I want to know if this is in fact demonstrably true and not just a matter of personal preference.
We will want to minimize the amount of resizing events, because each such event requires O(n) time where n is the number of elements in the list.
We also should be careful not to make the list too big because it might be a waste of memory.
Why does the author of my textbook say that 2 * array.length() is the magic number?
I read in a textbook that doubling the size of the array is the most efficient resizing. I want to know if this is in fact demonstrably true and not just a matter of personal preference.
We will want to minimize the amount of resizing events, because each such event requires O(n) time where n is the number of elements in the list.
We also should be careful not to make the list too big because it might be a waste of memory.
Why does the author of my textbook say that 2 * array.length() is the magic number?
Solution
Consider a model in which elements are only added, one at a time, and once an array is full, it is increased in size by a factor of $C$. Suppose also that resizing an array of size $x$ costs $Cx$. Adding $N = C^n$ elements (the worst case in terms of resizing cost per element) has cost $C(1+C+C^2+\cdots+C^n) \approx \frac{C^2}{C-1} N$. The amortized cost of adding an element is thus $f(C) = \frac{C^2}{C-1}$. The derivative of this function is
$$
f'(C) = \frac{2C(C-1)-C^2}{(C-1)^2} = \frac{C(2-C)}{(C-1)^2},
$$
which vanishes at $C=2$. It is not hard to check that this is a minimum of $f(C)$.
$$
f'(C) = \frac{2C(C-1)-C^2}{(C-1)^2} = \frac{C(2-C)}{(C-1)^2},
$$
which vanishes at $C=2$. It is not hard to check that this is a minimum of $f(C)$.
Context
StackExchange Computer Science Q#74350, answer score: 4
Revisions (0)
No revisions yet.