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.
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.
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.
An array stores a fixed-size sequential collection of elements of the same type, whereas list is a generic collection.
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.
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.
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