Conceptcore
Dynamic array
Also called growable array, resizable array, array list, ArrayList, vector, std::vector, Vec, List<T>, dynamic table.
A dynamic array keeps its items in an ordinary array with spare slots at the end. When the slots are full, it makes a bigger array and copies the items, so an append takes constant time on average.
- Applies to
- core-languages
Idea
An array has a fixed length, but most programs do not know at the start how many items they will keep. A dynamic array solves this problem with an ordinary array that is larger than it must be. Wikipedia describes it: "A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required. The elements of the dynamic array are stored contiguously at the start of the underlying array, and the remaining positions towards the end of the underlying array are reserved"1.
A dynamic array has two sizes:
- the length (or size, or count), the number of items in the list;
- the capacity, the number of slots in the array inside it.
An append that finds a free slot writes the item and adds 1 to the length. An append that finds no free slot must first grow the array: it makes a new, bigger array, copies every item into it and frees the old array. The trick is the size of the new array. If each new array is a constant factor bigger than the old one, such as twice as big, the copies are rare, and the average cost of an append is a constant. The task append to a list shows the append call in each language.
class DynamicArray:
"""A list that keeps its items in a fixed array and grows it when it is full."""
def __init__(self, factor=2.0):
self.factor = factor
self.capacity = 1
self.length = 0
self.slots = [None] * self.capacity
self.copies = 0
def append(self, item):
if self.length == self.capacity:
# Full: make a bigger array and copy every item into it.
new_capacity = max(self.capacity + 1, int(self.capacity * self.factor))
new_slots = [None] * new_capacity
for i in range(self.length):
new_slots[i] = self.slots[i]
self.copies += self.length
self.slots, self.capacity = new_slots, new_capacity
self.slots[self.length] = item
self.length += 1
def __getitem__(self, i):
if not 0 <= i < self.length:
raise IndexError(i)
return self.slots[i]
a = DynamicArray()
seen = []
for x in range(20):
a.append(x * 10)
if a.capacity not in seen:
seen.append(a.capacity)
print(a.length, a.capacity, a[19], seen)
def copies_for(n, grow):
"""Count the item copies that n appends make with a growth rule."""
capacity, copies = 1, 0
for length in range(n):
if length == capacity:
copies += length
capacity = grow(capacity)
return copies
n = 100_000
for name, grow in [("double", lambda c: 2 * c),
("times 1.5", lambda c: max(c + 1, c * 3 // 2)),
("plus 100", lambda c: c + 100)]:
c = copies_for(n, grow)
print(f"{name}: {c} copies, {c / n:.2f} per append")
20 32 190 [1, 2, 4, 8, 16, 32]
double: 131071 copies, 1.31 per append
times 1.5: 276521 copies, 2.77 per append
plus 100: 49951000 copies, 499.51 per append
Twenty appends grow the array only five times, through the capacities 2, 4, 8, 16 and 32. For 100,000 appends, doubling copies about 1.3 items for each append, and a growth factor of 1.5 copies about 2.8. A rule that adds 100 slots each time copies about 500 items for each append, and the number grows with n: the total work is quadratic.
How it works
Growth. Wikipedia gives the rule: "To avoid incurring the cost of resizing many times, dynamic arrays resize by a large amount, such as doubling in size, and use the reserved space for future expansion"1. With a growth factor a, the capacities form a geometric series. Wikipedia continues: "Expanding the array by any constant proportion a ensures that inserting n elements takes O(n) time overall, meaning that each insertion takes amortized constant time"1.
The reason is a sum. With doubling, the last growth copies at most n items, the one before it at most n / 2, the one before that n / 4, and so on. The sum n + n/2 + n/4 + ... is less than 2n. The page on amortized analysis says it in the same way: "the times for steps that scale the array add in a geometric series to O(n), while the constant times for each remaining push also add to O(n). Therefore the average time per push operation is O(n)/n=O(1)"2. A rule that adds a constant number of slots does not give this result. With a step of c slots, the copies are c + 2c + 3c + ..., which is about n * n / (2c).
Amortized time. Amortized constant time is a promise about a sequence of operations, not about each one. Most appends write one slot, and some appends copy the whole list. Java states the promise in these words: "The add, and addLast operations runs in amortized constant time, that is, adding n elements requires O(n) time"3. Rust says that, whatever growth rule Vec uses, it "will of course guarantee O(1) amortized push"4.
The growth factor. The factor is a trade between time and memory. Wikipedia says: "For growth factor a, the average time per insertion operation is about a/(a−1)"1, and a bigger factor leaves more slots empty. It also notes that a factor of 2 can work badly with some memory allocators, and that "There have been various discussions on ideal growth factor values, including proposals for the golden ratio as well as the value 1.5"1. The libraries use different rules:
- CPython grows a list by about one eighth, plus a small constant. The source code computes
newsize + (newsize >> 3) + 6, rounded to a multiple of 4, and the comment gives "The growth pattern is: 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, ..."5. - Java does not say. "The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost"3.
- Rust also does not say. "Vec does not guarantee any particular growth strategy when reallocating when full, nor when reserve is called"4. The Rust example shows the capacities 4, 8, 16, 32, 64 and 128 for
i32items. - Go doubles small slices and grows large slices more slowly. The runtime code has a comment about a "Transition from growing 2x for small slices" to "growing 1.25x for large slices"6, and it starts the change at a capacity of 256. The Go example shows the capacities 512, 848, 1280 and 1792 after this point. The runtime also rounds each size up to a size that its allocator uses.
- .NET
List<T>and libstdc++std::vectordouble in the example files: C# shows 4, 8, 16, 32, 64 and 128, and C++ shows 1, 2, 4, 8 and so on.
Operations. A dynamic array keeps the speed of an array for reads and writes. Wikipedia lists the costs: "Getting or setting the value at a particular index (constant time)", "Iterating over the elements in order (linear time, good cache performance)", "Inserting or deleting an element in the middle of the array (linear time)" and "Inserting or deleting an element at the end of the array (constant amortized time)"1. An insert at position i moves every item after i one slot to the right, so an insert at the front moves all the items. cppreference gives the same costs for std::vector: "Insertion or removal of elements at the end - amortized constant 𝓞(1)" and "Insertion or removal of elements - linear in the distance to the end of the vector 𝓞(n)"7.
Reserving memory. When the program knows the final number of items, it can make the capacity big enough at the start, and then no append copies. Java has ensureCapacity, and the documentation says: "This may reduce the amount of incremental reallocation"3. C# has EnsureCapacity, C++ has reserve, Rust has with_capacity and reserve, and Go has make([]T, 0, n). cppreference warns that "inappropriate uses of reserve() (for instance, calling it before every push_back() call) may actually increase the number of reallocations (by causing the capacity to grow linearly rather than exponentially)"8.
Shrinking. Most dynamic arrays do not give memory back when items are removed. Rust says: "Vec will never automatically shrink itself, even if completely empty"4. A program can ask for a smaller array with shrink_to_fit in Rust and C++, trimToSize in Java and TrimExcess in C#. .NET explains when to do it: "If the capacity is significantly larger than the count and you want to reduce the memory used by the List, you can decrease capacity by calling the TrimExcess method"9. Wikipedia notes that some dynamic arrays shrink by themselves when the length drops below a threshold, "such as 30% of the capacity"1.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript uses the JavaScript Array, typed as T[] or Array<T>. push, pop and length work as in JavaScript. No example file exists. |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Standard library | MutableListOf and ArrayList<E> give a dynamic array. On the JVM, kotlin.collections.ArrayList is java.util.ArrayList. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A table grows by rows, and the database manages the storage. Array column values in databases that have them are values, not growable buffers. |
| Bash | Native | An indexed array grows with a+=(x) or with an assignment to a new index. Bash does not store it as a contiguous array, and it has no capacity. No example file exists. |
| PowerShell | Standard library | [System.Collections.Generic.List[int]]::new() gives the .NET List<T> with Add and Capacity. The += operator on a PowerShell array makes a new array each time. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup. It has no collections. |
| CSS | Does not apply | CSS style rules have no collections. |
| Regular expressions | Does not apply | A regular expression matches text. It has no collections. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | list, a dynamic array of references with append, extend, insert and pop; the capacity is hidden |
| JavaScript | native | Array with push, pop, unshift and a writable length; resizable ArrayBuffer for bytes |
| TypeScript | native | the JavaScript Array, typed as T[] |
| Java | stdlib | java.util.ArrayList<E> with ensureCapacity and trimToSize; the capacity is hidden |
| Kotlin | stdlib | mutableListOf and ArrayList<E>, which is the Java class on the JVM |
| C# | stdlib | System.Collections.Generic.List<T> with Capacity, EnsureCapacity and TrimExcess |
| Go | native | slices with append, len and cap; make([]T, len, cap) reserves capacity |
| Rust | stdlib | Vec<T> with push, capacity, reserve, with_capacity and shrink_to_fit |
| C | idiom | a struct with a pointer, a length and a capacity, grown with realloc |
| C++ | stdlib | std::vector<T> with push_back, capacity, reserve and shrink_to_fit |
| Bash | native | indexed arrays grow with a+=(x); they are not stored as contiguous arrays |
| PowerShell | stdlib | [System.Collections.Generic.List[int]]::new() from .NET; += on an array copies the whole array |
| SQL | n/a | tables grow by rows; array columns where they exist are values, not growable buffers |
| Regex | n/a | a pattern matches text and has no collections |
| HTML | n/a | markup has no collections |
| CSS | n/a | style rules have no collections |
The dynamic array is the default list in most languages. The Python FAQ says: "CPython’s lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects"10. Java describes ArrayList as a "Resizable-array implementation of the List interface"3. .NET says that List<T> "implements the IList generic interface by using an array whose size is dynamically increased as required"11. Rust calls Vec<T> "A contiguous growable array type"4. cppreference says of std::vector: "The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements"7.
Go builds the dynamic array into the language with slices and the append function. The specification says: "If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise, append re-uses the underlying array"12. The Go blog says that this "technique is how dynamic array implementations from other languages work behind the scenes"13. C has no dynamic array in its library, so programs write a struct with a pointer, a length and a capacity, and they grow it with realloc.
JavaScript arrays hide their storage. The length of an array "represents the number of slots in that array"14, and the engine decides how to store the slots. A program can set length: a smaller value removes items, and "When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values"14. For binary data, "ArrayBuffer objects can be made resizable by including the maxByteLength option when calling the ArrayBuffer() constructor"15.
The example files show these forms. Python shows that a list asks for memory only now and then, and shows extend, pop, insert and a list made at its full size. JavaScript shows push, a writable length, holes, unshift and a resizable ArrayBuffer. Java shows ArrayList, ensureCapacity, trimToSize and the exception when a loop changes the list. C# prints the capacities of a List<T> and shows EnsureCapacity, TrimExcess and the same exception. Go prints the capacities of a slice and shows two appends that share one array. Rust prints the capacities of a Vec and shows with_capacity and shrink_to_fit. C builds a dynamic array with realloc. C++ prints the capacities of a std::vector and shows that a push past the capacity moves the items.
import sys
# A list is a dynamic array of references. append adds at the end.
a = []
sizes = []
for i in range(1000):
a.append(i)
sizes.append(sys.getsizeof(a))
# The list asks for more memory only now and then, not at each append.
resizes = sum(1 for x, y in zip(sizes, sizes[1:]) if y != x)
print(len(a), resizes < 100)
# extend adds many items in one call. pop removes the last item.
a.extend([1000, 1001])
print(len(a), a.pop(), len(a))
# insert at the front moves every other item one place to the right.
b = [1, 2, 3]
b.insert(0, 0)
print(b)
# [None] * n makes all the slots at once, so the loop only assigns.
c = [None] * 5
for i in range(5):
c[i] = i * i
print(c)
1000 True
1002 1001 1001
[0, 1, 2, 3]
[0, 1, 4, 9, 16]
- Verdict: native. The built-in list is a dynamic array of references. sys.getsizeof changes far fewer times than the 1000 appends, so the list grows its array now and then. extend and pop work at the end, insert at index 0 moves all the items, and [None] * n makes all the slots at once.
#include <iostream>
#include <vector>
int main() {
// std::vector grows its storage when size() reaches capacity().
std::vector<int> v;
std::vector<std::size_t> caps{v.capacity()};
for (int i = 0; i < 100; i++) {
v.push_back(i);
if (caps.back() != v.capacity()) {
caps.push_back(v.capacity());
}
}
std::cout << v.size() << ':';
for (auto c : caps) {
std::cout << ' ' << c;
}
std::cout << '\n';
// reserve gets the memory once, so the pushes do not move the items.
std::vector<int> w;
w.reserve(50);
const int* start = w.data();
for (int i = 0; i < 50; i++) {
w.push_back(i);
}
std::cout << (start == w.data()) << '\n';
// A push past the capacity moves the items. Old pointers then dangle.
std::vector<int> x{1, 2, 3};
x.shrink_to_fit();
const int* old = x.data();
x.push_back(4);
std::cout << (old == x.data()) << ' ' << x.size() << '\n';
}
100: 0 1 2 4 8 16 32 64 128
1
0 4
- Verdict: stdlib. std::vector in libstdc++ doubles its capacity from 1 to 128 while 100 items are added. After reserve(50), 50 pushes do not move the items. A push past the capacity moves the items to new memory, so the old pointer no longer equals data().
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
public class Main {
public static void main(String[] args) {
// ArrayList keeps its items in an array that grows when it is full.
ArrayList<Integer> a = new ArrayList<>();
for (int i = 0; i < 5; i++) {
a.add(i * 10);
}
System.out.println(a + " " + a.size() + " " + a.get(4));
// ensureCapacity grows the array once before many adds.
ArrayList<Integer> big = new ArrayList<>(10);
big.ensureCapacity(1_000_000);
for (int i = 0; i < 1_000_000; i++) {
big.add(i);
}
big.trimToSize();
System.out.println(big.size() + " " + big.getLast());
// add at index 0 moves every other item one place to the right.
a.add(0, -10);
a.removeLast();
System.out.println(a);
// A change to the list during a for-each loop makes the iterator fail.
List<Integer> c = new ArrayList<>(List.of(1, 2, 3));
try {
for (int x : c) {
if (x == 1) {
c.add(4);
}
}
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException");
}
}
}
[0, 10, 20, 30, 40] 5 40
1000000 999999
[-10, 0, 10, 20, 30]
ConcurrentModificationException
- Verdict: stdlib. ArrayList grows its array as add runs, and the capacity is not visible. ensureCapacity grows it once before a million adds, and trimToSize gives the spare slots back. add(0, x) moves the other items. A change to the list inside a for-each loop throws ConcurrentModificationException.
#include <stdio.h>
#include <stdlib.h>
/* A dynamic array: a pointer to the items, the number of items and the capacity. */
typedef struct {
int *items;
size_t len;
size_t cap;
} IntVec;
static int push(IntVec *v, int x, int *grows) {
if (v->len == v->cap) {
size_t new_cap = v->cap ? v->cap * 2 : 4;
int *p = realloc(v->items, new_cap * sizeof *p);
if (p == NULL) {
return -1; /* the old block is still valid */
}
v->items = p;
v->cap = new_cap;
(*grows)++;
}
v->items[v->len++] = x;
return 0;
}
int main(void) {
IntVec v = {NULL, 0, 0};
int grows = 0;
for (int i = 0; i < 1000; i++) {
if (push(&v, i * i, &grows) != 0) {
free(v.items);
return 1;
}
}
printf("%zu %zu %d %d\n", v.len, v.cap, grows, v.items[999]);
free(v.items);
return 0;
}
1000 1024 9 998001
- Verdict: idiom. The C library has no dynamic array. A struct keeps a pointer, a length and a capacity, and push doubles the capacity with realloc. 1000 pushes grow the array 9 times, from 4 slots to 1024. The result of realloc goes into a second variable, so a failure does not lose the old block.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// List<T> shows its Capacity, the length of the array inside it.
var list = new List<int>();
var caps = new List<int> { list.Capacity };
for (int i = 0; i < 100; i++)
{
list.Add(i);
if (caps[^1] != list.Capacity)
{
caps.Add(list.Capacity);
}
}
Console.WriteLine($"{list.Count}: {string.Join(" ", caps)}");
// EnsureCapacity grows the array once. TrimExcess gives the spare slots back.
var big = new List<int>();
big.EnsureCapacity(1000);
Console.WriteLine(big.Capacity >= 1000);
big.Add(1);
big.TrimExcess();
Console.WriteLine($"{big.Count} {big.Capacity}");
// Insert at index 0 moves every other item one place to the right.
var small = new List<int> { 2, 3 };
small.Insert(0, 1);
Console.WriteLine(string.Join(",", small));
// A change to the list during foreach makes the enumerator fail.
try
{
foreach (int x in small)
{
small.Add(x);
}
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.GetType().Name);
}
}
}
100: 0 4 8 16 32 64 128
True
1 1
1,2,3
InvalidOperationException
- Verdict: stdlib. List shows its Capacity, which doubles from 4 to 128 while 100 items are added. EnsureCapacity grows the array once, and TrimExcess makes the capacity equal to the count. Insert at index 0 moves the items. A change to the list inside foreach throws InvalidOperationException.
// An Array grows when a program pushes an item. push returns the new length.
const a = [];
console.log(a.push(10), a.push(20, 30), a);
// length is writable. A smaller length removes items, and a larger length adds holes.
a.length = 2;
console.log(a);
a.length = 4;
console.log(a, 3 in a);
// new Array(n) makes n holes, not n items. Array.from fills each slot.
console.log(new Array(3), Array.from({ length: 3 }, (_, i) => i * i));
// unshift adds at the front, so every other item moves.
const b = [2, 3];
b.unshift(1);
console.log(b);
// A resizable ArrayBuffer has a byte length and a maximum byte length.
const buf = new ArrayBuffer(8, { maxByteLength: 64 });
const ints = new Int32Array(buf); // no length: it tracks the buffer
console.log(buf.byteLength, buf.maxByteLength, ints.length);
buf.resize(16);
ints[3] = 7;
console.log(buf.byteLength, ints.length, Array.from(ints));
1 3 [ 10, 20, 30 ]
[ 10, 20 ]
[ 10, 20, <2 empty items> ] false
[ <3 empty items> ] [ 0, 1, 4 ]
[ 1, 2, 3 ]
8 64 2
16 4 [ 0, 0, 0, 7 ]
- Verdict: native. push returns the new length. A smaller length removes items, and a larger length adds empty slots, so 3 in a is false. new Array(3) makes holes, while Array.from fills the slots. A resizable ArrayBuffer grows to 16 bytes, and the Int32Array without a length tracks it.
package main
import "fmt"
func main() {
// A slice has a length and a capacity. append grows the backing array when it is full.
var s []int
caps := []int{}
for i := range 2000 {
s = append(s, i)
if len(caps) == 0 || caps[len(caps)-1] != cap(s) {
caps = append(caps, cap(s))
}
}
fmt.Println(len(s), caps)
// make with a capacity gets the memory once. append then does not reallocate.
t := make([]int, 0, 100)
before := cap(t)
for i := range 100 {
t = append(t, i)
}
fmt.Println(len(t), before == cap(t))
// Two appends to one slice with spare capacity write into the same array.
base := make([]int, 3, 4)
x := append(base, 1)
y := append(base, 2)
fmt.Println(x[3], y[3])
// When append reallocates, the new slice has its own array.
full := []int{1, 2, 3}
grown := append(full, 4)
grown[0] = 100
fmt.Println(full[0], grown[0])
}
2000 [4 8 16 32 64 128 256 512 848 1280 1792 2560]
100 true
2 2
1 100
- Verdict: native. append doubles the capacity of a small slice and grows a large slice by a smaller factor, rounded to the sizes of the allocator: 512, 848, 1280, 1792 and 2560. make with a capacity keeps the same array for 100 appends. Two appends to one slice with spare capacity share the array, so x[3] and y[3] are both 2.
fn main() {
// Vec<T> keeps the items in a heap buffer with a length and a capacity.
let mut v: Vec<i32> = Vec::new();
let mut caps = vec![v.capacity()];
for i in 0..100 {
v.push(i);
if *caps.last().unwrap() != v.capacity() {
caps.push(v.capacity());
}
}
println!("{} {:?}", v.len(), caps);
// with_capacity and reserve get the memory before the pushes.
let mut w = Vec::with_capacity(10);
let start = w.as_ptr();
for i in 0..10 {
w.push(i);
}
println!("{} {}", w.capacity() >= 10, start == w.as_ptr());
// A Vec does not shrink by itself. shrink_to_fit gives the memory back.
v.truncate(3);
let before = v.capacity();
v.shrink_to_fit();
println!("{} {} {}", v.len(), before >= 100, v.capacity() >= 3);
// insert(0, x) moves every other item one place to the right.
v.insert(0, -1);
println!("{:?}", v);
}
100 [0, 4, 8, 16, 32, 64, 128]
true true
3 true true
[-1, 0, 1, 2]
- Verdict: stdlib. Vec starts with capacity 0 and then has 4, 8, 16, 32, 64 and 128 slots for i32 items. with_capacity keeps the same buffer for 10 pushes. truncate keeps the large buffer, and shrink_to_fit makes it smaller. insert(0, x) moves the items.
Variations and related ideas
- Bounded arrays. Some arrays keep a count of the items in use but never grow. They work like a dynamic array with a fixed maximum capacity, and an append to a full array fails. A ring buffer is also bounded.
- Slices. A Go slice is a view of a dynamic array: "A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment)"13. Two slices can share one array, so an append to one can change the other. See slice.
- Deques and gap buffers. A plain dynamic array is fast only at the end. A double-ended queue, such as Python
collections.deque, JavaArrayDequeor RustVecDeque, is also fast at the front. A gap buffer keeps the free slots at the cursor of a text editor, so inserts near the cursor are fast. - Linked lists. The other common way to store a list is a linked list, a chain of cells with one item each. It inserts at the front in constant time but reaches item
iinisteps. - Persistent vectors. Functional languages such as Clojure and Scala use trees of small arrays, so a change makes a new version and keeps the old one.
- Strings and builders. A string builder, such as Java
StringBuilderor RustString, is a dynamic array of characters or bytes. See build a string efficiently. - Linked lists. A linked list adds at the front in constant time but reads item
iin linear time. Wikipedia compares them: a dynamic array has good "locality of reference and data cache utilization, compactness (low memory use), and random access"1.
Pitfalls
- Pointers into a dynamic array become invalid. When the array grows, the items move to new memory. cppreference says that after
push_back, if "the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated"16. A C or C++ pointer to an item then points to freed memory, which is a use after free. Rust rejects this program at compile time, because a reference to an item borrows theVec, andpushneeds a mutable borrow. See ownership. - A change during iteration. Java and C# detect a change to a list during a
forloop over it and throwConcurrentModificationExceptionorInvalidOperationException. Python does not detect it, and the loop can skip items or never end. - Shared backing in Go. Two appends to one slice that has spare capacity write into the same array. In the Go example,
xandyboth end with 2. When the program needs a separate slice, copy it first withslices.Clone. - An insert at the front in a loop.
insert(0, x),add(0, x)andunshiftmove all the items, soninserts at the front take quadratic time. Append and then reverse, or use a deque. - Growing by a constant. A custom dynamic array that adds a fixed number of slots, or a loop that grows a plain array by one with
Array.Resizeor PowerShell+=, does quadratic work. Grow by a factor. - Memory that is not given back. A list that once had a million items keeps the large array after
clearortruncate. Callshrink_to_fit,trimToSizeorTrimExcess, or make a new list. - realloc in C.
p = realloc(p, n)loses the old block ifreallocfails and returnsNULL. Keep the result in a second variable, as the C example does, and also check thatn * sizeof *pdoes not overflow. - reserve in a loop. In C++, a
reserve(size() + 1)before eachpush_backcan turn the geometric growth into linear growth, which is quadratic work8.
Cost
| Operation | Cost |
|---|---|
read or write item i |
constant |
| append at the end | amortized constant; linear when the array grows |
| remove at the end | constant |
insert or remove at position i |
linear in the number of items after i |
| iterate over all items | linear, with good cache use |
| extra memory | up to about (a - 1) * n slots for growth factor a |
A dynamic array uses more memory than a plain array with the same items. cppreference says: "Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted"7. Wikipedia gives the bound: "the number of wasted cells is bounded above by (a−1)n"1. The header is small: Rust and Go keep a pointer, a length and a capacity. The single growth step is slow, so a dynamic array is a poor choice where each append must finish within a fixed time, as in some real-time code.
History
Wikipedia lists dynamic arrays in many libraries: "C++'s std::vector and Rust's std::vec::Vec are implementations of dynamic arrays", and so are java.util.ArrayList in Java and System.Collections.ArrayList in the .NET Framework. It adds: "The generic System.Collections.Generic.List class in version 2.0 of the .NET Framework is also implemented with dynamic arrays"1. Java added ArrayList in version 1.2, with the Java Collections Framework, and the documentation says that it "is roughly equivalent to Vector, except that it is unsynchronized"3. Go made the dynamic array part of the language with slices and the built-in append12.
The analysis of the cost came later than the data structure. Wikipedia says that amortized analysis "was first formally introduced by Robert Tarjan in his 1985 paper Amortized Computational Complexity"2, and that "Dynamic arrays are a common example when teaching amortized analysis"1.
References
- Dynamic array, Wikipedia, Introduction; Bounded-size dynamic arrays and capacity; Geometric expansion and amortized cost; Growth factor; Performance; Language support
- Amortized analysis, Wikipedia, History; Dynamic array
- Class ArrayList, Java SE 25 API, Class description
- Struct Vec, The Rust Standard Library, Introduction; Capacity and reallocation; Guarantees
- Objects/listobject.c, CPython source code, list_resize
- src/runtime/slice.go, Go source code, nextslicecap
- std::vector, cppreference.com, Introduction
- std::vector::reserve, cppreference.com, Description; Notes
- List<T>.Capacity Property, .NET API reference, Remarks
- Design and History FAQ, Python documentation, How are lists implemented in CPython?
- List<T> Class, .NET API reference, Remarks
- The Go Programming Language Specification, Appending to and copying slices
- Go Slices, usage and internals, The Go Blog, Slice internals; Growing slices (the copy and append functions)
- Array length, MDN Web Docs, Description
- ArrayBuffer, MDN Web Docs, Resizing ArrayBuffers
- std::vector::push_back, cppreference.com, Description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag P9NS07 Edit this page History Report an error Markdown