A dynamic array is a resizable sequential container that stores elements in one contiguous block of memory and automatically allocates a larger block when it runs out of space. Among the data structures used in programming, it is the default general-purpose list: Python’s list, Java’s ArrayList, C++’s std::vector, Rust’s Vec and C#’s List<T> are all dynamic arrays.
It combines the constant-time random access of a fixed-size array with the convenience of a collection whose length changes at run time. The price is occasional reallocation and copying, which a geometric growth strategy spreads out so that appending costs amortized O(1) per element.
How a dynamic array grows
A dynamic array tracks two numbers: its size, the count of elements in use, and its capacity, the count of slots allocated. Appending writes into the next free slot while size is below capacity. When size reaches capacity, the structure allocates a new, larger buffer, copies or moves every existing element, frees the old buffer and then performs the append.
The key design decision is the growth factor. Multiplying capacity by a constant greater than one, rather than adding a fixed number of slots, guarantees that the total copying work stays proportional to the number of appends. Adding a constant increment instead leads to quadratic total cost, one of the classic performance mistakes.
Common runtime libraries use the following growth factors, which vary by implementation and version.
| Implementation | Approximate growth factor | Note |
|---|---|---|
| C++ std::vector (GCC, Clang) | 2 | Doubles capacity |
| C++ std::vector (MSVC) | 1.5 | Favors memory reuse |
| Java ArrayList | 1.5 | New capacity is old plus half |
| Python list | About 1.125 | Small overallocation plus a constant |
| Rust Vec | 2 | Minimum initial capacity applies |
| C# List | 2 | Starts at four elements |
A factor of 2 minimizes reallocations, whereas factors below the golden ratio of about 1.618 allow a memory allocator, in theory, to reuse previously freed blocks. Lower factors also waste less memory per array, which explains Python’s conservative choice.
Time complexity of dynamic array operations
Dynamic array performance follows from contiguous storage: any element’s address is the base address plus index times element size. Operations that do not shift elements are cheap, while operations in the middle require moving every later element.
| Operation | Average cost | Worst case | Reason |
|---|---|---|---|
| Read or write by index | O(1) | O(1) | Direct address arithmetic |
| Append at the end | Amortized O(1) | O(n) | Occasional reallocation |
| Remove from the end | O(1) | O(1) | Only the size changes |
| Insert or delete at front | O(n) | O(n) | All elements shift |
| Insert or delete in the middle | O(n) | O(n) | Later elements shift |
| Linear search | O(n) | O(n) | No ordering assumed |
Amortized analysis explains the append cost. With doubling, inserting n elements copies at most about 2n elements in total, because the copies form a geometric series of n/2, n/4 and so on. Individual appends may still take O(n), which matters in latency-sensitive or real-time code where a single reallocation pause is unacceptable.
Dynamic array compared with related structures
The dynamic array competes mainly with the fixed-size array, the linked list and the deque. Its advantage over linked lists is larger than asymptotic notation suggests, because contiguous memory makes full use of CPU caches and hardware prefetching.
| Structure | Indexing | Append | Front insertion | Memory locality |
|---|---|---|---|---|
| Dynamic array | O(1) | Amortized O(1) | O(n) | Excellent |
| Fixed-size array | O(1) | Not possible beyond capacity | O(n) | Excellent |
| Linked list | O(n) | O(1) with tail pointer | O(1) | Poor |
| Deque | O(1) | Amortized O(1) | Amortized O(1) | Good |
In benchmarks, a dynamic array often outperforms a linked list even for middle insertions on moderate sizes, since shifting a contiguous block with a single memory move is faster than chasing pointers to reach the insertion point. Dynamic arrays also serve as the backing store for stacks, binary heaps and hash table buckets.
Using dynamic arrays effectively
Most performance gains come from controlling capacity explicitly. When the final element count is known or can be estimated, reserving it in advance eliminates all intermediate reallocations.
- Call
reservein C++,with_capacityin Rust or pass an initial capacity to Java’sArrayListto pre-allocate storage. - Use
shrink_to_fitortrimToSizeafter bulk removals to return unused memory, accepting a possible reallocation. - Prefer removing from the end or swapping the target with the last element when order does not matter, which turns O(n) deletion into O(1).
- Store values rather than pointers where possible, so iteration benefits from cache locality.
Most implementations do not shrink automatically when elements are removed, because shrinking at the same threshold as growing would cause thrashing when size oscillates around a boundary. Implementations that do shrink typically wait until the array is only one quarter full.
Pitfalls and failure modes
The most dangerous pitfall in languages with manual memory management is iterator and pointer invalidation. Any reallocation moves the elements, so pointers, references or iterators obtained earlier become dangling, which leads to undefined behavior in C and C++.
| Symptom | Likely cause | Fix |
|---|---|---|
| Crash or corrupted data after append | Invalidated pointer or iterator | Reacquire references after growth |
| Slow loop that builds a large list | Repeated reallocation | Reserve capacity up front |
| High memory use after deletions | Capacity never released | Shrink explicitly |
| Quadratic slowdown on insertions | Front or middle insertion in a loop | Use a deque or build then reverse |
| Occasional latency spikes | Large reallocation copy | Pre-allocate or use a chunked structure |
Very large dynamic arrays can also fail to allocate even when enough total memory exists, because growth requires a single contiguous block large enough for the new capacity while the old block is still held.
In everyday language
A dynamic array is like a row of numbered lockers that you can open instantly by number. When every locker is full and a new item arrives, the system rents a bigger row of lockers, moves everything over and continues.
Moving everything takes effort, but because the new row is usually twice as long, moves happen rarely. On average, adding an item stays fast and predictable, which is why most programs use this structure as their everyday list.
Seen in the real world
A backend service parses a log file of about five million lines and collects matching records into a Java ArrayList. Starting from the default small capacity, the list reallocates roughly thirty times as it grows by half each time, copying many millions of references along the way.
After profiling, the developer counts lines first and creates the list with that initial capacity. The reallocations disappear, peak memory drops because no two large buffers coexist during a copy, and the parsing step runs noticeably faster with smoother garbage collection pauses.