Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<long> vs long[], memory usage

Tags:

c#

.net

memory

Regarding the size in memory for the

List<long> ListOfLongs;
long[] ArrayOfLongs;

If each has N elements, how much memory they eat up?

I am asking that because as of my knowledge, .NET has not template (generics) specialization.

like image 628
Daniel Mošmondor Avatar asked Dec 11 '11 16:12

Daniel Mošmondor


People also ask

Which takes more memory list or array?

The array is probably taking more memory because of the way you constructed it. If you do floats = array. array('d', L) then the array will occupy less memory than the list. But not much less.

Which is faster array or list?

The array is faster in case of access to an element while List is faster in case of adding/deleting an element from the collection.

What is the difference between a list and an array in c#?

An array stores a fixed-size sequential collection of elements of the same type, whereas list is a generic collection.


2 Answers

Practically the same amount of memory (technically, the List will probably consume some more because it has over-allocated so that it can grow more easily).

Generic collections in .NET do not need to box the items they hold, which would be a massive memory and performance sink.

like image 62
Jon Avatar answered Sep 18 '22 11:09

Jon


The List<T> owns an array T[]. It uses an exponential growth strategy for this array, so a list with n elements usually has a backing array with size larger than n. Also the smaller arrays need to be garbage collected, which can be annoying if the are large enough to be on the LoH.

But you can avoid this by specifying a capacity manually, for example as a constructor parameter. Then a single array with the desired capacity will be allocated, so you avoid both of the above problems.

In addition List<T> has a small O(1) overhead for the list object itself.


But there is no per element overhead when using generics. The runtime creates a specialized version for each value type you pass in. No boxing of the elements occurs.

But you can't use C++ style template specialization, where you effectively overload the implementation for certain type parameters. All generic instantiations share the same C# code.

i.e. there is no specialized IL code, but each value type gets a specialized machine code implementation based on the same source-code.

like image 43
CodesInChaos Avatar answered Sep 17 '22 11:09

CodesInChaos