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