Dynamic array

On this page 7

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.

ImplementationApproximate growth factorNote
C++ std::vector (GCC, Clang)2Doubles capacity
C++ std::vector (MSVC)1.5Favors memory reuse
Java ArrayList1.5New capacity is old plus half
Python listAbout 1.125Small overallocation plus a constant
Rust Vec2Minimum initial capacity applies
C# List2Starts at four elements
Typical growth factors in standard libraries

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.

OperationAverage costWorst caseReason
Read or write by indexO(1)O(1)Direct address arithmetic
Append at the endAmortized O(1)O(n)Occasional reallocation
Remove from the endO(1)O(1)Only the size changes
Insert or delete at frontO(n)O(n)All elements shift
Insert or delete in the middleO(n)O(n)Later elements shift
Linear searchO(n)O(n)No ordering assumed
Cost of common operations

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.

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.

StructureIndexingAppendFront insertionMemory locality
Dynamic arrayO(1)Amortized O(1)O(n)Excellent
Fixed-size arrayO(1)Not possible beyond capacityO(n)Excellent
Linked listO(n)O(1) with tail pointerO(1)Poor
DequeO(1)Amortized O(1)Amortized O(1)Good
Dynamic array versus neighboring structures

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 reserve in C++, with_capacity in Rust or pass an initial capacity to Java’s ArrayList to pre-allocate storage.
  • Use shrink_to_fit or trimToSize after 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++.

SymptomLikely causeFix
Crash or corrupted data after appendInvalidated pointer or iteratorReacquire references after growth
Slow loop that builds a large listRepeated reallocationReserve capacity up front
High memory use after deletionsCapacity never releasedShrink explicitly
Quadratic slowdown on insertionsFront or middle insertion in a loopUse a deque or build then reverse
Occasional latency spikesLarge reallocation copyPre-allocate or use a chunked structure
Common symptoms, causes and fixes

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.