<p>I've always been told that adding an element to an array happens like this:</p>

<blockquote>
  <p>An empty copy of the array+1element is
  created and then the data from the
  original array is copied into it then
  the new data for the new element is
  then loaded</p>
</blockquote>

<p>If this is true, then using an array within a scenario that requires a lot of element activity is contra-indicated due to memory and CPU utilization, correct?</p>

<p>If that is the case, shouldn't you try to avoid using an array as much as possible when you will be adding a lot of elements? Should you use iStringMap instead? If so, what happens if you need more than two dimensions AND need to add a lot of element additions. Do you just take the performance hit or is there something else that should be used?</p>

[{'answer_id': 75995, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 2, 'selected': False, 'text': "<p>When the array is resized, a new array must be allocated, and the contents copied.  If you are only modifying the contents of the array, it is just a memory assignment.  </p>\n\n<p>So, you should not use arrays when you don't know the size of the array, or the size is likely to change.  However, if you have a fixed length array, they are an easy way of retrieving elements by index.</p>\n"}, {'answer_id': 76001, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 6, 'selected': True, 'text': '<p>Look at the generic <code>List&lt;T&gt;</code> as a replacement for arrays.  They support most of the same things arrays do, including allocating an initial storage size if you want.  </p>\n'}, {'answer_id': 76004, 'author': 'Jon', 'author_id': 12261, 'author_profile': 'https://Stackoverflow.com/users/12261', 'pm_score': 1, 'selected': False, 'text': '<p>The best thing you can do is to allocate as much memory as you need upfront if possible. This will prevent <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a> from having to make additional calls to get memory on the heap. Failing that then it makes sense to allocate in chunks of five or whatever number makes sense for your application.</p>\n\n<p>This is a rule you can apply to anything really.</p>\n'}, {'answer_id': 76008, 'author': 'user13288', 'author_id': 13288, 'author_profile': 'https://Stackoverflow.com/users/13288', 'pm_score': 1, 'selected': False, 'text': '<p>A standard array should be defined with a length, which reserves all of the memory that it needs in a contiguous block. Adding an item to the array would put it inside of the block of already reserved memory.</p>\n'}, {'answer_id': 76021, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 3, 'selected': False, 'text': "<p>In general, I prefer to avoid array usage.  Just use List&lt;T>.  It uses a dynamically-sized array internally, and is fast enough for most usage.  If you're using multi-dimentional arrays, use List&lt;List&lt;List&lt;T>>> if you have to.  It's not that much worse in terms of memory, and is much simpler to add items to.</p>\n\n<p>If you're in the 0.1% of usage that requires extreme speed, make sure it's your list accesses that are really the problem before you try to optimize it.</p>\n"}, {'answer_id': 76022, 'author': 'Tom Ritter', 'author_id': 8435, 'author_profile': 'https://Stackoverflow.com/users/8435', 'pm_score': 2, 'selected': False, 'text': "<p>ArrayList and List grow the array by more than one when needed (I think it's by doubling the size, but I haven't checked the source).  They are generally the best choice when you are building a dynamically sized array.</p>\n\n<p>When your benchmarks indicate that array resize is seriously slowing down your application (remember - premature optimization is the root of all evil), you can evaluate writing a custom array class with tweaked resizing behavior.</p>\n"}, {'answer_id': 76023, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 1, 'selected': False, 'text': '<p>Arrays are great for few writes and many reads, particularly those of an iterative nature - for anything else, use one of the many other data structures.</p>\n'}, {'answer_id': 76034, 'author': 'apenwarr', 'author_id': 42219, 'author_profile': 'https://Stackoverflow.com/users/42219', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re going to be adding/removing elements a lot, just use a List.  If it\'s multidimensional, you can always use a List&lt;List&lt;int>> or something.</p>\n\n<p>On the other hand, lists are less efficient than arrays if what you\'re mostly doing is <em>traversing</em> the list, because arrays are all in one place in your CPU cache, where objects in a list are scattered all over the place.</p>\n\n<p>If you want to use an array for efficient reading but you\'re going to be "adding" elements frequently, you have two main options:</p>\n\n<p>1) Generate it as a List (or List of Lists) and then use ToArray() to turn it into an efficient array structure.</p>\n\n<p>2) Allocate the array to be larger than you need, then put the objects into the pre-allocated cells.  If you end up needing even more elements than you pre-allocated, you can just reallocate the array when it fills, doubling the size each time.  This gives O(log n) resizing performance instead of O(n) like it would be with a reallocate-once-per-add array.  Note that this is pretty much how StringBuilder works, giving you a faster way to continually append to a string.</p>\n'}, {'answer_id': 76056, 'author': 'Sam', 'author_id': 9406, 'author_profile': 'https://Stackoverflow.com/users/9406', 'pm_score': 1, 'selected': False, 'text': "<p>You are correct an array is great for look ups. However modifications to the size of the array are costly.</p>\n\n<p>You should use a container that supports incremental size adjustments in the scenario where you're modifying the size of the array. You could use an ArrayList which allows you to set the initial size, and you could continually check the size versus the capacity and then increment the capacity by a large chunk to limit the number of resizes.</p>\n\n<p>Or you could just use a linked list. Then however look ups are slow...</p>\n"}, {'answer_id': 76059, 'author': 'Alex Lyman', 'author_id': 5897, 'author_profile': 'https://Stackoverflow.com/users/5897', 'pm_score': 4, 'selected': False, 'text': '<p>This really depends on what you mean by "add."</p>\n\n<p>If you mean:</p>\n\n<pre><code>T[] array;\nint i;\nT value;\n...\nif (i &gt;= 0 &amp;&amp; i &lt;= array.Length)\n    array[i] = value;\n</code></pre>\n\n<p>Then, no, this does not create a new array, and is in-fact the fastest way to alter any kind of IList in .NET.</p>\n\n<p>If, however, you\'re using something like ArrayList, List, Collection, etc. then calling the "Add" method <em>may</em> create a new array -- but they are smart about it, they don\'t just resize by 1 element, they grow geometrically, so if you\'re adding lots of values only every once in a while will it have to allocate a new array.  Even then, you can use the "Capacity" property to force it to grow before hand, if you know how many elements you\'re adding (<code>list.Capacity += numberOfAddedElements</code>)</p>\n'}, {'answer_id': 76361, 'author': 'John Christensen', 'author_id': 1194, 'author_profile': 'https://Stackoverflow.com/users/1194', 'pm_score': 1, 'selected': False, 'text': "<p>If I think I'm going to be adding items to the collection a lot over its lifetime, than I'll use a List. If I know for sure what the size of the collection will be when its declared, then I'll use an array.</p>\n\n<p>Another time I generally use an array over a List is when I need to return a collection as a property of an object - I don't want callers adding items that collection via List's Add methods, but instead want them to add items to the collection via my object's interface. In that case, I'll take the internal List and call ToArray and return an array.</p>\n"}, {'answer_id': 76458, 'author': 'Rick Minerich', 'author_id': 9251, 'author_profile': 'https://Stackoverflow.com/users/9251', 'pm_score': 2, 'selected': False, 'text': '<p>Generally, if you must have the BEST indexed lookup performance it\'s best to build a List first and then turn it into a array thus paying a small penalty at first but avoiding any later. If the issue is that you will be continually adding new data and removing old data then you may want to use a ArrayList or List for convenience but keep in mind that they are just special case Arrays. When they "grow" they allocate a completely new array and copy everything into it which is extremely slow.</p>\n\n<p><a href="http://blogs.msdn.com/bclteam/articles/273454.aspx" rel="nofollow noreferrer">ArrayList</a> is just an Array which grows when needed. \nAdd is amortized O(1), just be careful to make sure the resize won\'t happen at a bad time.\nInsert is O(n) all items to the right must be moved over.\nRemove is O(n) all items to the right must be moved over.</p>\n\n<p>Also important to keep in mind that List is not a linked list. It\'s just a typed ArrayList. The List <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="nofollow noreferrer">documentation</a> does note that it performs better in most cases but does not say why.</p>\n\n<p>The best thing to do is to pick a data structure which is appropriate to your problem. This depends one a LOT of things and so you may want to browse the <a href="http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx" rel="nofollow noreferrer">System.Collections.Generic</a> Namespace. </p>\n\n<p>In this particular case I would say that if you can come up with a good key value <a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="nofollow noreferrer">Dictionary</a> would be your best bet. It has insert and remove that approaches O(1). However, even with a Dictionary you have to be careful not to let it resize it\'s internal array (an O(n) operation). It\'s best to give them a lot of room by specifying a larger-then-you-expect-to-use initial capacity in the constructor. </p>\n\n<p>-Rick</p>\n'}, {'answer_id': 76520, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 1, 'selected': False, 'text': '<p>If you are going to be doing a lot of adding, <em>and</em> you will not be doing random access (such as <code>myArray[i]</code>).  You could consider using a linked list (<code>LinkedList&lt;T&gt;</code>), because it will never have to "grow" like the <code>List&lt;T&gt;</code> implementation.  Keep in mind, though, that you can only really access items in a <code>LinkedList&lt;T&gt;</code> implementation using the <code>IEnumerable&lt;T&gt;</code> interface.</p>\n'}, {'answer_id': 19907490, 'author': 'nawfal', 'author_id': 661933, 'author_profile': 'https://Stackoverflow.com/users/661933', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n<p>When to abandon the use of arrays</p>\n</blockquote>\n<ol>\n<li><p>First and foremost, <em>when semantics of arrays <strong>dont</strong> match with your intent</em> - Need a dynamically growing collection? A set which doesn\'t allow duplicates? A collection that has to remain immutable? Avoid arrays in all that cases. That\'s 99% of the cases. Just stating the obvious basic point.</p>\n</li>\n<li><p>Secondly, <em>when you are <strong>not</strong> coding for absolute performance criticalness</em> - That\'s about 95% of the cases. <a href="https://stackoverflow.com/questions/1168915/which-one-is-more-efficient-listint-or-int">Arrays perform better <em>marginally</em></a>, <a href="https://stackoverflow.com/questions/454916/performance-of-arrays-vs-lists">especially in iteration</a>. It almost always never matter.</p>\n</li>\n<li><p><em>When you\'re <strong>not</strong> forced by an argument with <code>params</code> keyword</em> - I just wished <code>params</code> accepted any <code>IEnumerable&lt;T&gt;</code> or even better a language construct itself to denote a <em>sequence</em> (and not a framework type).</p>\n</li>\n<li><p><em>When you are <strong>not</strong> writing legacy code, or dealing with interop</em></p>\n</li>\n</ol>\n<p>In short, its very rare that you would actually need an array. I will add as to why may one avoid it?</p>\n<ol>\n<li><p>The biggest reason to avoid arrays imo is conceptual. Arrays are closer to implementation and farther from abstraction. Arrays conveys more <em>how it is done</em> than <em>what is done</em> which is against the spirit of high level languages. That\'s not surprising, considering arrays are closer to the metal, they are straight out of a special type (though internally array is a class). Not to be pedagogical, but arrays really do translate to a semantic meaning very very rarely required. The most useful and frequent semantics are that of a collections with any entries, sets with distinct items, key value maps etc with any combination of addable, readonly, immutable, order-respecting variants. Think about this, you might want an addable collection, or readonly collection with predefined items with no further modification, but how often does your logic look like &quot;I want a dynamically addable collection but only a fixed number of them and they should be modifiable too&quot;? Very rare I would say.</p>\n</li>\n<li><p>Array was designed during pre-generics era and it mimics genericity with lot of run time hacks and it will show its oddities here and there. Some of the catches I found:</p>\n<ol>\n<li><p><a href="https://stackoverflow.com/questions/4317459/why-is-array-co-variance-considered-so-horrible">Broken covariance.</a></p>\n<pre><code> string[] strings = ...\n object[] objects = strings;\n objects[0] = 1; //compiles, but gives a runtime exception.\n</code></pre>\n</li>\n<li><p><a href="https://stackoverflow.com/questions/6705583/indexers-in-list-vs-array">Arrays can give you reference to a struct!</a>. That\'s unlike anywhere else. A sample:</p>\n<pre><code> struct Value { public int mutable; }\n\n var array = new[] { new Value() };  \n array[0].mutable = 1; //&lt;-- compiles !\n //a List&lt;Value&gt;[0].mutable = 1; doesnt compile since editing a copy makes no sense\n print array[0].mutable // 1, expected or unexpected? confusing surely\n</code></pre>\n</li>\n<li><p><a href="https://stackoverflow.com/questions/19888123/t-contains-for-struct-and-class-behaving-differently">Run time implemented methods like <code>ICollection&lt;T&gt;.Contains</code> can be different for structs and classes</a>. It\'s not a big deal, but if you forget to override <em>non generic <code>Equals</code></em> correctly for reference types expecting generic collection to look for <em>generic <code>Equals</code></em>, you will get incorrect results.</p>\n<pre><code> public class Class : IEquatable&lt;Class&gt;\n {\n     public bool Equals(Class other)\n     {\n         Console.WriteLine(&quot;generic&quot;);\n         return true;\n     }\n     public override bool Equals(object obj)\n     {\n         Console.WriteLine(&quot;non generic&quot;);\n         return true;\n     } \n }\n\n public struct Struct : IEquatable&lt;Struct&gt;\n {\n     public bool Equals(Struct other)\n     {\n         Console.WriteLine(&quot;generic&quot;);\n         return true;\n     }\n     public override bool Equals(object obj)\n     {\n         Console.WriteLine(&quot;non generic&quot;);\n         return true;\n     } \n }\n\n class[].Contains(test); //prints &quot;non generic&quot;\n struct[].Contains(test); //prints &quot;generic&quot;\n</code></pre>\n</li>\n<li><p>The <code>Length</code> property and <code>[]</code> indexer on <code>T[]</code> seem to be regular properties that you can access through reflection (which should involve some magic), but when it comes to expression trees you have to spit out the exact same code the compiler does. There are <code>ArrayLength</code> and <code>ArrayIndex</code> methods to do that separately. One such <a href="https://stackoverflow.com/questions/19336342/how-to-get-memberinfo-of-arraylength-type-expressions">question here</a>. Another example:</p>\n<pre><code> Expression&lt;Func&lt;string&gt;&gt; e = () =&gt; new[] { &quot;a&quot; }[0];\n //e.Body.NodeType == ExpressionType.ArrayIndex\n\n Expression&lt;Func&lt;string&gt;&gt; e = () =&gt; new List&lt;string&gt;() { &quot;a&quot; }[0];\n //e.Body.NodeType == ExpressionType.Call;\n</code></pre>\n</li>\n<li><p><a href="https://stackoverflow.com/questions/26475362/why-does-ilisttarray-readonly-true-but-ilistarray-readonly-false">Yet another one</a>. <code>string[].IsReadOnly</code> returns <code>false</code>, but if you are casting, <code>IList&lt;string&gt;.IsReadOnly</code> returns <code>true</code>.</p>\n</li>\n<li><p>Type checking gone wrong: <code>(object)new ConsoleColor[0] is int[]</code> returns <code>true</code>, whereas <code>new ConsoleColor[0] is int[]</code> returns <code>false</code>. Same is true for <code>uint[]</code> and <code>int[]</code> comparisons. No such problems if you use any other collection types.</p>\n</li>\n</ol>\n</li>\n</ol>\n<blockquote>\n<p>How to abandon the use of arrays.</p>\n</blockquote>\n<p>The most commonly used substitute is <code>List&lt;T&gt;</code> which has a cleaner API. But it is a dynamically growing structure which means you can add to a <code>List&lt;T&gt;</code> at the end or insert anywhere to any capacity. There is no substitute for the exact behaviour of an array, but people mostly use arrays as readonly collection where you can\'t add anything to its end. A substitute is <code>ReadOnlyCollection&lt;T&gt;</code>.</p>\n'}]
['https://Stackoverflow.com/questions/75976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/730/']