# Dynamic array

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Dynamic_array
> Markdown URL: https://mediated.wiki/source/Dynamic_array.md
> Source: https://en.wikipedia.org/wiki/Dynamic_array
> Source revision: 1350863115
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

List data structure to which elements can be added/removed

Several values are inserted at the end of a dynamic array using geometric expansion. Grey cells indicate space reserved for expansion. Most insertions are fast ([constant time](/source/Constant_time)), while some are slow due to the need for [reallocation](/source/Memory_management) (Θ(*n*) time, labelled with turtles). The *logical size* and *capacity* of the final array are shown.

In [computer science](/source/Computer_science), a **dynamic array**, **growable array**, **resizable array**, **dynamic table**, **mutable array**, or **array list** is a [random access](/source/Random_access), variable-size [list data structure](/source/List_data_structure) that allows elements to be added or removed. It is supplied with [standard libraries](/source/Standard_libraries) in many modern mainstream [programming languages](/source/Programming_language). Dynamic arrays overcome a limit of static [arrays](/source/Array_data_type), which have a fixed capacity that needs to be specified at [allocation](/source/Memory_management).

A dynamic array is not the same thing as a [dynamically allocated](/source/Dynamic_memory_allocation) array or [variable-length array](/source/Variable-length_array), either of which is an array whose size is fixed when the array is allocated, although a dynamic array may use such a fixed-size array as a back end.[1]

## Bounded-size dynamic arrays and capacity

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. Elements can be added at the end of a dynamic array in [constant time](/source/Time_complexity#Constant_time) by using the reserved space until this space is completely consumed.

When all space is consumed and an additional element is to be added, the underlying fixed-size array needs to be increased in size. Typically, resizing is expensive because it involves allocating a new underlying array and possibly copying each element from the original array.

Elements can be removed from the end of a dynamic array in constant time, as no resizing is required. The number of elements used by the dynamic array contents is its *logical size* or *length*, while the size of the underlying array is called the dynamic array's *physical size* or *capacity*. The capacity is the maximum possible size without relocating data.[2]

A fixed-size array will suffice in applications where the maximum logical size is fixed (e.g. by specification), or can be calculated before the array is allocated. A dynamic array might be preferred if:

- the maximum logical size is unknown, or difficult to calculate, before the array is allocated

- it is considered that a maximum logical size given by a specification is likely to change

- the amortized cost of resizing a dynamic array does not significantly affect performance or responsiveness

## Geometric expansion and amortized cost

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. The operation of adding an element to the end might work as follows:

function insertEnd(dynarray a, element e)
    if (a.size == a.capacity)
        // resize a to twice its current capacity:
        a.capacity ← a.capacity * 2
        // (copy the contents to the new memory location here)
    a[a.size] ← e
    a.size ← a.size + 1

As *n* elements are inserted, the capacities form a [geometric progression](/source/Geometric_progression). Expanding the array by any constant proportion *a* ensures that inserting *n* elements takes [*O*(*n*)](/source/Big_O_notation) time overall, meaning that each insertion takes [amortized](/source/Amortized_analysis) constant time (so long as any given allocation takes *O*(*1*) time). Many dynamic arrays also deallocate some of the underlying storage if its size drops below a certain threshold, such as 30% of the capacity. This threshold must be strictly smaller than 1/*a* in order to provide [hysteresis](/source/Hysteresis) (provide a stable band to avoid repeatedly growing and shrinking) and support mixed sequences of insertions and removals with amortized constant cost.

Dynamic arrays are a common example when teaching [amortized analysis](/source/Amortized_analysis).[3][4]

## Growth factor

The growth factor for the dynamic array depends on several factors including a space-time trade-off and algorithms used in the memory allocator itself. For growth factor *a*, the average time per insertion operation is about *a*/(*a*−1), while the number of wasted cells is bounded above by (*a*−1)*n*[*[citation needed](https://en.wikipedia.org/wiki/Wikipedia:Citation_needed)*]. If memory allocator uses a [first-fit allocation](/source/First_fit_algorithm) algorithm, then growth factor values such as *a*=2 can cause dynamic array expansion to run out of memory even though a significant amount of memory may still be available.[5] There have been various discussions on ideal growth factor values, including proposals for the [golden ratio](/source/Golden_ratio) as well as the value 1.5.[6] Many textbooks, however, use *a* = 2 for simplicity and analysis purposes.[3][4]

Below are growth factors used by several popular implementations:

Implementation Growth factor (a) Java ArrayList[1] 1.5 (3/2) Python PyListObject[7] ~1.125 (n + (n >> 3)) Microsoft Visual C++ 2013[8] 1.5 (3/2) G++ 5.2.0[5] 2 Clang 3.6[5] 2 Facebook folly/FBVector[9] 1.5 (3/2) Unreal Engine TArray[10] ~1.375 (n + ((3 * n) >> 3)) Rust Vec[11] 2 Go slices[12] between 1.25 and 2 Nim sequences[13] 2 SBCL (Common Lisp) vectors[14] 2 C# (.NET 8) List 2

## Performance

Comparison of list data structures Peek (index) Mutate (insert or delete) at … Excess space, average Beginning End Middle Linked list Θ(n) Θ(1) Θ(1), known end element; Θ(n), unknown end element Θ(n) Θ(n) Array Θ(1) —N/a —N/a —N/a 0 Dynamic array Θ(1) Θ(n) Θ(1) amortized Θ(n) Θ(n)[15] Balanced tree Θ(log n) Θ(log n) Θ(log n) Θ(log n) Θ(n) Random-access list Θ(log n)[16] Θ(1) —N/a[16] —N/a[16] Θ(n) Hashed array tree Θ(1) Θ(n) Θ(1) amortized Θ(n) Θ(√n)

The dynamic array has performance similar to an array, with the addition of new operations to add and remove elements:

- 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)

- Inserting or deleting an element at the end of the array (constant amortized time)

Dynamic arrays benefit from many of the advantages of arrays, including good [locality of reference](/source/Locality_of_reference) and [data cache](/source/Data_cache) utilization, compactness (low memory use), and [random access](/source/Random_access). They usually have only a small fixed additional overhead for storing information about the size and capacity. This makes dynamic arrays an attractive tool for building [cache](/source/Cache_(computing))-friendly [data structures](/source/Data_structure). However, in languages like Python or Java that enforce reference semantics, the dynamic array generally will not store the actual data, but rather it will store [references](/source/Reference_(computer_science)) to the data that resides in other areas of memory. In this case, accessing items in the array sequentially will actually involve accessing multiple non-contiguous areas of memory, so the many advantages of the cache-friendliness of this data structure are lost.

Compared to [linked lists](/source/Linked_list), dynamic arrays have faster indexing (constant time versus linear time) and typically faster iteration due to improved locality of reference; however, dynamic arrays require linear time to insert or delete at an arbitrary location, since all following elements must be moved, while linked lists can do this in constant time. This disadvantage is mitigated by the [gap buffer](/source/Gap_buffer) and *tiered vector* variants discussed under *Variants* below. Also, in a highly [fragmented](/source/Fragmentation_(computer)) memory region, it may be expensive or impossible to find contiguous space for a large dynamic array, whereas linked lists do not require the whole data structure to be stored contiguously.

A [balanced tree](/source/Self-balancing_binary_search_tree) can store a list while providing all operations of both dynamic arrays and linked lists reasonably efficiently, but both insertion at the end and iteration over the list are slower than for a dynamic array, in theory and in practice, due to non-contiguous storage and tree traversal/manipulation overhead.

## Variants

[Gap buffers](/source/Gap_buffer) are similar to dynamic arrays but allow efficient insertion and deletion operations clustered near the same arbitrary location. Some [deque](/source/Deque) implementations use [array deques](/source/Deque#Implementations), which allow amortized constant time insertion/removal at both ends, instead of just one end.

Goodrich[17] presented a dynamic array algorithm called *tiered vectors* that provides *O*(*n*1/*k*) performance for insertions and deletions from anywhere in the array, and *O*(*k*) get and set, where *k* ≥ 2 is a constant parameter.

[Hashed array tree](/source/Hashed_array_tree) (HAT) is a dynamic array algorithm published by Sitarski in 1996.[18] Hashed array tree wastes order *n*1/2 amount of storage space, where *n* is the number of elements in the array. The algorithm has *O*(1) amortized performance when appending a series of objects to the end of a hashed array tree.

In a 1999 paper,[19] Brodnik et al. describe a tiered dynamic array data structure, which wastes only *n*1/2 space for *n* elements at any point in time, and they prove a lower bound showing that any dynamic array must waste this much space if the operations are to remain amortized constant time. Additionally, they present a variant where growing and shrinking the buffer has not only amortized but worst-case constant time.

Bagwell (2002)[20] presented the VList algorithm, which can be adapted to implement a dynamic array.

Naïve resizable arrays -- also called "the worst implementation" of resizable arrays -- keep the allocated size of the array exactly big enough for all the data it contains, perhaps by calling [realloc](/source/Realloc) for each and every item added to the array. Naïve resizable arrays are the simplest way of implementing a resizable array in C. They don't waste any memory, but appending to the end of the array always takes Θ(*n*) time.[18][21][22][23][24] Linearly growing arrays pre-allocate ("waste") Θ(1) space every time they re-size the array, making them many times faster than naïve resizable arrays -- appending to the end of the array still takes Θ(*n*) time but with a much smaller constant. Naïve resizable arrays and linearly growing arrays may be useful when a space-constrained application needs lots of small resizable arrays; they are also commonly used as an educational example leading to exponentially growing dynamic arrays.[25]

## Language support

[C++](/source/C%2B%2B)'s [std::vector](/source/Vector_(C%2B%2B)) and [Rust](/source/Rust_(programming_language))'s std::vec::Vec are implementations of dynamic arrays, as are java.util.ArrayList[26] in [Java](/source/Java_(programming_language))[27]: 236 and System.Collections.ArrayList in the [.NET Framework](/source/.NET_Framework).[28][29]: 22

The generic System.Collections.Generic.List<T> class in version 2.0 of the [.NET Framework](/source/.NET_Framework) is also implemented with dynamic arrays. [Smalltalk](/source/Smalltalk)'s OrderedCollection is a dynamic array with dynamic start and end-index, making the removal of the first element also O(1).

[Python](/source/Python_(Programming_Language))'s list datatype implementation is a dynamic array, the growth pattern of which is: 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, ...[7]

[Delphi](/source/Delphi_(programming_language)) and [D](/source/D_(programming_language)) implement dynamic arrays at the language's core.

[Ada](/source/Ada_(programming_language))'s [Ada.Containers.Vectors](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Containers.Vectors) generic package provides dynamic array implementation for a given subtype.

Many scripting languages such as [Perl](/source/Perl) and [Ruby](/source/Ruby_(programming_language)) offer dynamic arrays as a built-in [primitive data type](/source/Primitive_data_type).

Several cross-platform frameworks provide dynamic array implementations for [C](/source/C_(programming_language)), including CFArray and CFMutableArray in [Core Foundation](/source/Core_Foundation), and GArray and GPtrArray in [GLib](/source/GLib).

[Common Lisp](/source/Common_Lisp) provides a rudimentary support for resizable vectors by allowing to configure the built-in array type as *adjustable* and the location of insertion by the *fill-pointer*.

## See also

- [Stack (abstract data type)](/source/Stack_(abstract_data_type))

- [Queue (abstract data type)](/source/Queue_(abstract_data_type))

## References

1. ^ [***a***](#cite_ref-java_util_ArrayList_1-0) [***b***](#cite_ref-java_util_ArrayList_1-1) See, for example, the [source code of java.util.ArrayList class from OpenJDK 6](http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/e0e25ac28560/src/share/classes/java/util/ArrayList.java).

1. **[^](#cite_ref-2)** Lambert, Kenneth Alfred (2009), ["Physical size and logical size"](https://books.google.com/books?id=VtfM3YGW5jYC&q=%22logical+size%22+%22dynamic+array%22&pg=PA518), *Fundamentals of Python: From First Programs Through Data Structures*, Cengage Learning, p. 510, [ISBN](/source/ISBN_(identifier)) [978-1423902188](https://en.wikipedia.org/wiki/Special:BookSources/978-1423902188){{[citation](https://en.wikipedia.org/wiki/Template:Citation)}}: CS1 maint: work parameter with ISBN ([link](https://en.wikipedia.org/wiki/Category:CS1_maint:_work_parameter_with_ISBN))

1. ^ [***a***](#cite_ref-gt-ad_3-0) [***b***](#cite_ref-gt-ad_3-1) [Goodrich, Michael T.](/source/Michael_T._Goodrich); [Tamassia, Roberto](/source/Roberto_Tamassia) (2002), "1.5.2 Analyzing an Extendable Array Implementation", *Algorithm Design: Foundations, Analysis and Internet Examples*, Wiley, pp. 39–41.

1. ^ [***a***](#cite_ref-clrs_4-0) [***b***](#cite_ref-clrs_4-1) [Cormen, Thomas H.](/source/Thomas_H._Cormen); [Leiserson, Charles E.](/source/Charles_E._Leiserson); [Rivest, Ronald L.](/source/Ron_Rivest); [Stein, Clifford](/source/Clifford_Stein) (2001) [1990]. "17.4 Dynamic tables". [*Introduction to Algorithms*](/source/Introduction_to_Algorithms) (2nd ed.). MIT Press and McGraw-Hill. pp. 416–424. [ISBN](/source/ISBN_(identifier)) [0-262-03293-7](https://en.wikipedia.org/wiki/Special:BookSources/0-262-03293-7).

1. ^ [***a***](#cite_ref-C++_STL_vector_5-0) [***b***](#cite_ref-C++_STL_vector_5-1) [***c***](#cite_ref-C++_STL_vector_5-2) ["C++ STL vector: definition, growth factor, member functions"](https://web.archive.org/web/20150806162750/http://www.gahcep.com/cpp-internals-stl-vector-part-1/). Archived from [the original](http://www.gahcep.com/cpp-internals-stl-vector-part-1/) on 2015-08-06. Retrieved 2015-08-05.

1. **[^](#cite_ref-6)** ["vector growth factor of 1.5"](http://arquivo.pt/wayback/20110122130054/https://groups.google.com/forum/#!topic/comp.lang.c++.moderated/asH_VojWKJw%5B1-25%5D). *comp.lang.c++.moderated*. Google Groups. Archived from [the original](https://groups.google.com/forum/#!topic/comp.lang.c++.moderated/asH_VojWKJw%5B1-25%5D) on 2011-01-22. Retrieved 2015-08-05.

1. ^ [***a***](#cite_ref-cpython_listobject.c_growth_rate_comment_7-0) [***b***](#cite_ref-cpython_listobject.c_growth_rate_comment_7-1) ["cpython/Objects/listobject.c at bace59d8b8e38f5c779ff6296ebdc0527f6db14a - python/cpython"](https://github.com/python/cpython/blob/bace59d8b8e38f5c779ff6296ebdc0527f6db14a/Objects/listobject.c#L58). *GitHub*. Retrieved 2026-03-27.

1. **[^](#cite_ref-8)** Brais, Hadi (15 November 2013). ["Dissecting the C++ STL Vector: Part 3 - Capacity & Size"](https://hadibrais.wordpress.com/2013/11/15/dissecting-the-c-stl-vector-part-3-capacity/). *Micromysteries*. Retrieved 2015-08-05.

1. **[^](#cite_ref-9)** ["facebook/folly"](https://github.com/facebook/folly/blob/master/folly/docs/FBVector.md). *GitHub*. Retrieved 2015-08-05.

1. **[^](#cite_ref-10)** ["Nested TArrays in structs and memory"](https://forums.unrealengine.com/t/nested-tarrays-in-structs-and-memory/2357416/3). *Epic Developer Community Forums*. 2025-02-26. Retrieved 2025-05-26.

1. **[^](#cite_ref-11)** ["rust-lang/rust"](https://github.com/rust-lang/rust/blob/b90dc1e597db0bbc0cab0eccb39747b1a9d7e607/library/alloc/src/raw_vec/mod.rs#L521). *GitHub*. Retrieved 2026-03-01.

1. **[^](#cite_ref-12)** ["golang/go"](https://github.com/golang/go/blob/master/src/runtime/slice.go#L188). *GitHub*. Retrieved 2021-09-14.

1. **[^](#cite_ref-13)** ["The Nim memory model"](http://zevv.nl/nim-memory/#_growing_a_seq). *zevv.nl*. Retrieved 2022-05-24.

1. **[^](#cite_ref-14)** ["sbcl/sbcl"](https://github.com/sbcl/sbcl/blob/master/src/code/array.lisp#L1200-L1204). *GitHub*. Retrieved 2023-02-15.

1. **[^](#cite_ref-15)** Brodnik, Andrej; Carlsson, Svante; [Sedgewick, Robert](/source/Robert_Sedgewick_(computer_scientist)); Munro, JI; Demaine, ED (1999), [*Resizable Arrays in Optimal Time and Space (Technical Report CS-99-09)*](http://www.cs.uwaterloo.ca/research/tr/1999/09/CS-99-09.pdf) (PDF), Department of Computer Science, University of Waterloo

1. ^ [***a***](#cite_ref-okasakiComparison_16-0) [***b***](#cite_ref-okasakiComparison_16-1) [***c***](#cite_ref-okasakiComparison_16-2) Chris Okasaki (1995). "Purely Functional Random-Access Lists". *Proceedings of the Seventh International Conference on Functional Programming Languages and Computer Architecture*: 86–95. [doi](/source/Doi_(identifier)):[10.1145/224164.224187](https://doi.org/10.1145%2F224164.224187).

1. **[^](#cite_ref-17)** [Goodrich, Michael T.](/source/Michael_T._Goodrich); Kloss II, John G. (1999), ["Tiered Vectors: Efficient Dynamic Arrays for Rank-Based Sequences"](https://archive.org/details/algorithmsdatast0000wads/page/205), *[Workshop on Algorithms and Data Structures](/source/Workshop_on_Algorithms_and_Data_Structures)*, Lecture Notes in Computer Science, **1663**: [205–216](https://archive.org/details/algorithmsdatast0000wads/page/205), [doi](/source/Doi_(identifier)):[10.1007/3-540-48447-7_21](https://doi.org/10.1007%2F3-540-48447-7_21), [ISBN](/source/ISBN_(identifier)) [978-3-540-66279-2](https://en.wikipedia.org/wiki/Special:BookSources/978-3-540-66279-2){{[citation](https://en.wikipedia.org/wiki/Template:Citation)}}: CS1 maint: work parameter with ISBN ([link](https://en.wikipedia.org/wiki/Category:CS1_maint:_work_parameter_with_ISBN))

1. ^ [***a***](#cite_ref-sitarski96_18-0) [***b***](#cite_ref-sitarski96_18-1) Sitarski, Edward (September 1996), ["HATs: Hashed array trees"](http://www.ddj.com/architect/184409965?pgno=5), Algorithm Alley, *Dr. Dobb's Journal*, **21** (11)

1. **[^](#cite_ref-brodnik_19-0)** Brodnik, Andrej; Carlsson, Svante; [Sedgewick, Robert](/source/Robert_Sedgewick_(computer_scientist)); Munro, JI; Demaine, ED (1999), [*Resizable Arrays in Optimal Time and Space*](http://www.cs.uwaterloo.ca/research/tr/1999/09/CS-99-09.pdf) (PDF) (Technical Report CS-99-09), Department of Computer Science, University of Waterloo

1. **[^](#cite_ref-20)** Bagwell, Phil (2002), [*Fast Functional Lists, Hash-Lists, Deques and Variable Length Arrays*](http://citeseer.ist.psu.edu/bagwell02fast.html), EPFL

1. **[^](#cite_ref-21)** Mike Lam. ["Dynamic Arrays"](https://w3.cs.jmu.edu/lam2mo/cs240_2015_08/files/04-dyn_arrays.pdf).

1. **[^](#cite_ref-22)** ["Amortized Time"](https://users.cs.northwestern.edu/~jesse/course/cs214-fa19/lec/17-amortized.pdf).

1. **[^](#cite_ref-23)** ["Hashed Array Tree: Efficient representation of Array"](https://iq.opengenus.org/hashed-array-tree/).

1. **[^](#cite_ref-24)** ["Different notions of complexity"](https://people.ksp.sk/~kuko/gnarley-trees/Complexity2.html).

1. **[^](#cite_ref-25)** Peter Kankowski. ["Dynamic arrays in C"](https://www.strchr.com/dynamic_arrays).

1. **[^](#cite_ref-26)** Javadoc on [ArrayList](https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/util/ArrayList.html)

1. **[^](#cite_ref-Bloch_27-0)** Bloch, Joshua (2018). *"Effective Java: Programming Language Guide"* (third ed.). Addison-Wesley. [ISBN](/source/ISBN_(identifier)) [978-0134685991](https://en.wikipedia.org/wiki/Special:BookSources/978-0134685991).

1. **[^](#cite_ref-28)** [ArrayList Class](https://msdn.microsoft.com/en-us/library/system.collections.arraylist)

1. **[^](#cite_ref-Skeet_29-0)** Skeet, Jon (23 March 2019). *C# in Depth*. Manning. [ISBN](/source/ISBN_(identifier)) [978-1617294532](https://en.wikipedia.org/wiki/Special:BookSources/978-1617294532).

## External links

- [NIST Dictionary of Algorithms and Data Structures: Dynamic array](https://xlinux.nist.gov/dads/HTML/dynamicarray.html)

- [VPOOL](http://www.bsdua.org/libbsdua.html#vpool) - C language implementation of dynamic array.

- [CollectionSpy](https://web.archive.org/web/20090704095801/http://www.collectionspy.com/) — A Java profiler with explicit support for debugging ArrayList- and Vector-related issues.

- [Open Data Structures - Chapter 2 - Array-Based Lists](http://opendatastructures.org/versions/edition-0.1e/ods-java/2_Array_Based_Lists.html), [Pat Morin](/source/Pat_Morin)

v t e Data structures Types Collection Container Abstract Associative array Multimap Retrieval Data Structure List Stack Queue Double-ended queue Priority queue Double-ended priority queue Set Multiset Disjoint-set Arrays Bit array Circular buffer Dynamic array Hash table Hashed array tree Sparse matrix Linked Association list Linked list Skip list Unrolled linked list XOR linked list Trees B-tree Binary search tree AA tree AVL tree Red–black tree Self-balancing tree Splay tree Heap Binary heap Binomial heap Fibonacci heap R-tree R* tree R+ tree Hilbert R-tree Rope Trie Hash tree Graphs Binary decision diagram Directed acyclic graph Directed acyclic word graph List of data structures

---
Adapted from the Wikipedia article [Dynamic array](https://en.wikipedia.org/wiki/Dynamic_array) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Dynamic_array?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
