Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more efficient: List<T>.Add() or System.Array.Resize()?

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

like image 690
makerofthings7 Avatar asked Jan 18 '11 04:01

makerofthings7


People also ask

Which is better list or array?

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.

Is it better to use array or list C#?

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.

In what situation should you use a list instead of an array of T?

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.

Which method is used to resize an array?

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.


Video Answer


1 Answers

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.

like image 104
SLaks Avatar answered Oct 05 '22 04:10

SLaks