I'm trying to determine when it's more efficient to List<T>.Add()
versus using the Array.Resize()
method.
The documentation for Array.Resize says it makes a copy of the entire array, and places it into a new object. The old object would have to be discarded. Where does this old object reside? On the stack or the heap?
I don't know how List.Add() works.
Does anyone know how the List.Add method compares to the static Array.Resize method?
I'm interested in memory usage (and cleanup), and what is better for 300 value types, versus 20,000 value types.
For what it's worth, I'm planning on running this code on one of the embedded flavors of .NET. Potentially the .NET Gadgeteer
The list is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. List occupies much more memory as every node defined the List has its own memory set whereas Arrays are memory-efficient data structure.
In general, it's better to use lists in C# because lists are far more easily sorted, searched through, and manipulated in C# than arrays. That's because of all of the built-in list functionalities in the language.
Definitely use a List<T> any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some very specific reason (after benchmarking), then an array may be useful.
Resize(T[], Int32) Method is used to resize the number of elements present in the array. Or in other words, this method is used to change the number of elements of a one-dimensional array to the specified new size. It resizes the only 1-D array, not multidimensional array.
You should use a List<T>
.
Using Array.Resize
will force you to expand the array separately each time you add an item, making your code much slower. (since arrays cannot have spare capacity)
A List<T>
is backed by an array, but holds spare capacity to put items into.
All it needs to do to add an item is to set an element in the array and increase its internal size
counter.
When the array gets full, the list will double its capacity, allowing future items to be added effortlessly again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With