Dynamic array

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), while some are slow due to the need for reallocation (Θ(n) time, labelled with turtles). The logical size and capacity of the final array are shown.

In computer science, a dynamic array, growable array, resizable array, dynamic table, mutable array, or array list is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern mainstream programming languages. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that needs to be specified at allocation.

A dynamic array is not the same thing as a dynamically allocated array or 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, or unused. Elements can be added at the end of a dynamic array in 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, then the underlying fixed-size array needs to be increased in size. Typically resizing is expensive because it involves allocating a new underlying array and 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 size, while the size of the underlying array is called the dynamic array's capacity or physical size, which 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. 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. 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 (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.[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]. If memory allocator uses a first-fit allocation 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 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)
Rust Vec[10] 2
Go slices[11] between 1.25 and 2
Nim sequences[12] 2
SBCL (Common Lisp) vectors[13] 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)[14][15] Θ(n)
Array Θ(1) 0
Dynamic array Θ(1) Θ(n) Θ(1) amortized Θ(n) Θ(n)[16]
Balanced tree Θ(log n) Θ(log n) Θ(log n) Θ(log n) Θ(n)
Random-access list Θ(log n)[17] Θ(1) [17] [17] Θ(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 and data cache utilization, compactness (low memory use), and 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-friendly data structures. 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 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, 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 and tiered vector variants discussed under Variants below. Also, in a highly fragmented 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 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 are similar to dynamic arrays but allow efficient insertion and deletion operations clustered near the same arbitrary location. Some deque implementations use array deques, which allow amortized constant time insertion/removal at both ends, instead of just one end.

Goodrich[18] presented a dynamic array algorithm called tiered vectors that provides O(n1/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 (HAT) is a dynamic array algorithm published by Sitarski in 1996.[19] Hashed array tree wastes order n1/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,[20] Brodnik et al. describe a tiered dynamic array data structure, which wastes only n1/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)[21] 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 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.[19][22][23][24][25] 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.[26]

Language support

C++'s std::vector and Rust's std::vec::Vec are implementations of dynamic arrays, as are the ArrayList[27] classes supplied with the Java API[28]: 236  and the .NET Framework.[29][30]: 22 

The generic List<> class supplied with version 2.0 of the .NET Framework is also implemented with dynamic arrays. Smalltalk's OrderedCollection is a dynamic array with dynamic start and end-index, making the removal of the first element also O(1).

Python's list datatype implementation is a dynamic array the growth pattern of which is: 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, ...[31]

Delphi and D implement dynamic arrays at the language's core.

Ada's Ada.Containers.Vectors generic package provides dynamic array implementation for a given subtype.

Many scripting languages such as Perl and Ruby offer dynamic arrays as a built-in primitive data type.

Several cross-platform frameworks provide dynamic array implementations for C, including CFArray and CFMutableArray in Core Foundation, and GArray and GPtrArray in GLib.

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

References

  1. ^ a b See, for example, the source code of java.util.ArrayList class from OpenJDK 6.
  2. ^ Lambert, Kenneth Alfred (2009), "Physical size and logical size", Fundamentals of Python: From First Programs Through Data Structures, Cengage Learning, p. 510, ISBN 978-1423902188
  3. ^ a b Goodrich, Michael T.; Tamassia, Roberto (2002), "1.5.2 Analyzing an Extendable Array Implementation", Algorithm Design: Foundations, Analysis and Internet Examples, Wiley, pp. 39–41.
  4. ^ a b Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001) [1990]. "17.4 Dynamic tables". Introduction to Algorithms (2nd ed.). MIT Press and McGraw-Hill. pp. 416–424. ISBN 0-262-03293-7.
  5. ^ a b c "C++ STL vector: definition, growth factor, member functions". Archived from the original on 2015-08-06. Retrieved 2015-08-05.
  6. ^ "vector growth factor of 1.5". comp.lang.c++.moderated. Google Groups. Archived from the original on 2011-01-22. Retrieved 2015-08-05.
  7. ^ List object implementation from github.com/python/cpython/, retrieved 2020-03-23.
  8. ^ Brais, Hadi. "Dissecting the C++ STL Vector: Part 3 - Capacity & Size". Micromysteries. Retrieved 2015-08-05.
  9. ^ "facebook/folly". GitHub. Retrieved 2015-08-05.
  10. ^ "rust-lang/rust". GitHub. Retrieved 2020-06-09.
  11. ^ "golang/go". GitHub. Retrieved 2021-09-14.
  12. ^ "The Nim memory model". zevv.nl. Retrieved 2022-05-24.
  13. ^ "sbcl/sbcl". GitHub. Retrieved 2023-02-15.
  14. ^ Day 1 Keynote - Bjarne Stroustrup: C++11 Style at GoingNative 2012 on channel9.msdn.com from minute 45 or foil 44
  15. ^ Number crunching: Why you should never, ever, EVER use linked-list in your code again at kjellkod.wordpress.com
  16. ^ Brodnik, Andrej; Carlsson, Svante; Sedgewick, Robert; Munro, JI; Demaine, ED (1999), Resizable Arrays in Optimal Time and Space (Technical Report CS-99-09) (PDF), Department of Computer Science, University of Waterloo
  17. ^ a b c Chris Okasaki (1995). "Purely Functional Random-Access Lists". Proceedings of the Seventh International Conference on Functional Programming Languages and Computer Architecture: 86–95. doi:10.1145/224164.224187.
  18. ^ Goodrich, Michael T.; Kloss II, John G. (1999), "Tiered Vectors: Efficient Dynamic Arrays for Rank-Based Sequences", Workshop on Algorithms and Data Structures, Lecture Notes in Computer Science, 1663: 205–216, doi:10.1007/3-540-48447-7_21, ISBN 978-3-540-66279-2
  19. ^ a b Sitarski, Edward (September 1996), "HATs: Hashed array trees", Algorithm Alley, Dr. Dobb's Journal, 21 (11)
  20. ^ Brodnik, Andrej; Carlsson, Svante; Sedgewick, Robert; Munro, JI; Demaine, ED (1999), Resizable Arrays in Optimal Time and Space (PDF) (Technical Report CS-99-09), Department of Computer Science, University of Waterloo
  21. ^ Bagwell, Phil (2002), Fast Functional Lists, Hash-Lists, Deques and Variable Length Arrays, EPFL
  22. ^ Mike Lam. "Dynamic Arrays".
  23. ^ "Amortized Time".
  24. ^ "Hashed Array Tree: Efficient representation of Array".
  25. ^ "Different notions of complexity".
  26. ^ Peter Kankowski. "Dynamic arrays in C".
  27. ^ Javadoc on ArrayList
  28. ^ Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN 978-0134685991.
  29. ^ ArrayList Class
  30. ^ Skeet, Jon. C# in Depth. Manning. ISBN 978-1617294532.
  31. ^ listobject.c (github.com)

Read other articles:

Historic church in Rhode Island, United States United States historic placeHoly Trinity Church ComplexU.S. National Register of Historic Places Postcard of Holy Trinity ChurchShow map of Rhode IslandShow map of the United StatesLocationCentral Falls, Rhode IslandCoordinates41°53′19″N 71°23′47″W / 41.88861°N 71.39639°W / 41.88861; -71.39639Built1889ArchitectJames Murphy; Irving GormanArchitectural styleGothic RevivalMPSCentral Falls MRA (AD)NRHP refer…

Octobre 1813 Nombre de jours 31 Premier jour Vendredi 1er octobre 18135e jour de la semaine 39 Dernier jour Dimanche 31 octobre 18137e jour de la semaine 43 Calendrier octobre 1813 Sem Lu Ma Me Je Ve Sa Di 39 1er 2 3 40 4 5 6 7 8 9 10 41 11 12 13 14 15 16 17 42 18 19 20 21 22 23 24  43 25 26 27 28 29 30 31 1813 • Années 1810 • XIXe siècle Mois précédent et suivant Septembre 1813 Novembre 1813 Octobre précédent et suivant Octobre 1812 Octobre 1814 Chronologies p…

Family of birds Not to be confused with Hylidae, a family of amphibians. Hyliidae Green hylia (Hylia prasina) Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Aves Order: Passeriformes Superfamily: Sylvioidea Family: HyliidaeBannerman, 1923 Genera Hylia Pholidornis Hyliidae is a family of passerine birds which contains just two species, the green hylia (Hylia prasina) and the tit hylia (Pholidornis rushiae). Physiological similarities and molecular phylogenet…

Ethnogenesis of Romanians Part of a series on the History of Romania Prehistory Cucuteni–Trypillia culture Hamangia culture Bronze Age in Romania Prehistory of Transylvania Antiquity Dacia Dacian Wars Roman Dacia Origin of the Romanians Middle Ages (Early) History of Transylvania Banat in the Middle Ages First Bulgarian Empire Second Bulgarian Empire Voivodeship of Maramureș Founding of Wallachia Founding of Moldavia Rumelia Eyalet Early Modern Times Silistra Eyalet Principality of Transylvan…

Soap opera character Darryl BraxtonHome and Away characterPortrayed bySteve PeacockeDuration2011–2016First appearance16 February 2011Last appearance7 June 2016ClassificationFormer; regularIntroduced byCameron WelshBook appearancesHome and Away: New Beginnings[1]In-universe informationOccupationBusinessman[2]FatherDanny BraxtonMotherCheryl BraxtonBrothersHeath BraxtonHalf-brothersKyle BraxtonCasey BraxtonSonsCasey BraxtonNephewsRocco Scott-BraxtonHarley …

  关于位於加勒比海的荷屬島嶼,请见「薩巴」。 沙巴Sabah州 州旗州徽颂歌:Sabah Tanah Airku《沙巴我的故土》   沙巴   马来西亚其它州属坐标:5°18′N 117°00′E / 5.3°N 117°E / 5.3; 117首府亞庇省份 列表 西海岸省山打根省古達省內陸省斗湖省 政府[1][2] • 邦元首朱哈·马希鲁丁 • 首席部长哈芝芝·诺面积[3]&#…

Bight in the Gulf of Guinea This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Bight of Benin – news · newspapers · books · scholar · JSTOR (December 2021) (Learn how and when to remove this message) Bight of BeninGolfe du Bénin (French)Gulf of Guinea map showing the Bight of Benin.Bight of BeninCoordinates5…

Sophie ThalmannThalmann in 2013.Lahir7 Mei 1976 (umur 48)Bar-le-Duc, Meuse, FranceTinggi5 ft 11 in (1,80 m)GelarMiss France 1998Suami/istriChristophe SoumillonAnak2Pemenang kontes kecantikanKompetisiutamaMiss Lorraine 1997Miss MeuseMiss Universe 1998 Situs websophie-thalmann.com Sophie Thalmann (lahir 7 Mei 1976) adalah mantan ratu kecantikan, model, dan presenter televisi berkebangsaan Prancis. Dia mendapatkan gelar Miss Lorraine pada 1997 dan Miss Prancis pada tahun 1998. D…

Pécy La mairie. Blason Administration Pays France Région Île-de-France Département Seine-et-Marne Arrondissement Provins Intercommunalité Communauté de communes Val Briard Maire Mandat Bruno Gainand 2020-2026 Code postal 77970 Code commune 77357 Démographie Gentilé Péciacquois Populationmunicipale 846 hab. (2021 ) Densité 40 hab./km2 Géographie Coordonnées 48° 39′ 24″ nord, 3° 04′ 45″ est Altitude Min. 109 mMax. 145 m Superf…

Державний комітет телебачення і радіомовлення України (Держкомтелерадіо) Приміщення комітетуЗагальна інформаціяКраїна  УкраїнаДата створення 2003Керівне відомство Кабінет Міністрів УкраїниРічний бюджет 1 964 898 500 ₴[1]Голова Олег НаливайкоПідвідомчі орг…

British zoologist (1878–1943) Charles Regan FRSBorn1 February 1878 (1878-02)SherborneDied12 January 1943 (1943-01-13) (aged 64)NationalityBritishOccupationichthyologistKnown forfish classification schemes Charles Tate Regan FRS[1] (1 February 1878 – 12 January 1943) was a British ichthyologist, working mainly around the beginning of the 20th century. He did extensive work on fish classification schemes. Born in Sherborne, Dorset, he was educated at Derby School an…

Pour les articles homonymes, voir Marry Me. Cet article est une ébauche concernant une chanson, la Finlande et le Concours Eurovision de la chanson. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Marry Me Single de Krista Siegfridsextrait de l'album Ding Dong Sortie 1er janvier 2013 Durée 3 min 02 Langue Anglais Genre Dance-pop Format Téléchargement Auteur-compositeur Krista Siegfrieds, Erik Nyholm, Kristo…

Russian wheelchair fencer Ludmila VasilevaPersonal informationBorn (1984-10-18) 18 October 1984 (age 39)Belozersk, Soviet UnionSportCountryRussiaSportWheelchair fencing Medal record Event 1st 2nd 3rd Paralympic Games 0 0 1 World Championships 1 4 2 European Championships 4 1 5 Total 5 5 8 Paralympic Games 2020 Tokyo Foil B Ludmila Vasileva (born 18 October 1984 in Belozersk, Soviet Union) is a Russian wheelchair fencer. She fences in the foil and épée in category B. Ludmila is a four-time…

此条目序言章节没有充分总结全文内容要点。 (2019年3月21日)请考虑扩充序言,清晰概述条目所有重點。请在条目的讨论页讨论此问题。 哈萨克斯坦總統哈薩克總統旗現任Қасым-Жомарт Кемелұлы Тоқаев卡瑟姆若马尔特·托卡耶夫自2019年3月20日在任任期7年首任努尔苏丹·纳扎尔巴耶夫设立1990年4月24日(哈薩克蘇維埃社會主義共和國總統) 哈萨克斯坦 哈萨克斯坦政府與…

ヨハネス12世 第130代 ローマ教皇 教皇就任 955年12月16日教皇離任 964年5月14日先代 アガペトゥス2世次代 レオ8世個人情報出生 937年スポレート公国(中部イタリア)スポレート死去 964年5月14日 教皇領、ローマ原国籍 スポレート公国親 父アルベリーコ2世(スポレート公)、母アルダその他のヨハネステンプレートを表示 ヨハネス12世(Ioannes XII、937年 - 964年5月14日)は、ロー…

本條目存在以下問題,請協助改善本條目或在討論頁針對議題發表看法。 此條目需要編修,以確保文法、用詞、语气、格式、標點等使用恰当。 (2013年8月6日)請按照校對指引,幫助编辑這個條目。(幫助、討論) 此條目剧情、虛構用語或人物介紹过长过细,需清理无关故事主轴的细节、用語和角色介紹。 (2020年10月6日)劇情、用語和人物介紹都只是用於了解故事主軸,輔助讀…

ميت عباد  -  قرية مصرية -  تقسيم إداري البلد  مصر المحافظة محافظة الدقهلية المركز نبروه المسؤولون السكان التعداد السكاني 1853 نسمة (إحصاء 2006) معلومات أخرى التوقيت ت ع م+02:00  تعديل مصدري - تعديل   قرية ميت عباد هي إحدى القرى التابعة لمركز نبروه في محافظة الدقهلية ف…

Diócesis de San Miguel Dioecesis Sancti Michaelis (en latín) Catedral basílica santuario Nuestra Señora de la PazInformación generalIglesia católicaIglesia sui iuris latinaRito romanoSufragánea de arquidiócesis de San SalvadorPatronazgo • san Miguel Arcángel• Nuestra Señora de la PazFecha de erección 11 de febrero de 1913 (como diócesis)SedeCatedral basílica santuario Nuestra Señora de la PazCiudad San Migueldepartamento San MiguelPaís El Salvador El SalvadorCuria diocesa…

Classe KiloProgetto 877 PaltusUn Classe Kilo in navigazione, 1987Descrizione generale TipoSSK Proprietà Voenno-morskoj flot Cantiere/ Amur Shipbuilding / Admiralty Shipyard / Sevmash Impostazione16 marzo 1980 Varo12 settembre 1980 Entrata in servizio31 dicembre 1980 Caratteristiche generaliDislocamentoin immersione: 3025 t Stazza lorda2325 tsl Lunghezza72,6 m Larghezza9,9 m Altezza6,6 m Profondità operativa250 m PropulsioneDiesel-Elettrica Velocitàin immersione: 1…

Questa voce o sezione sull'argomento Storia è priva o carente di note e riferimenti bibliografici puntuali. Sebbene vi siano una bibliografia e/o dei collegamenti esterni, manca la contestualizzazione delle fonti con note a piè di pagina o altri riferimenti precisi che indichino puntualmente la provenienza delle informazioni. Puoi migliorare questa voce citando le fonti più precisamente. Segui i suggerimenti del progetto di riferimento. Pagina in minuscola carolina La rinascita carolingi…