List <long> vs long [], memory usage

Regarding size in memory for

List<long> ListOfLongs; long[] ArrayOfLongs; 

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

I ask that since, as far as I know, .NET does not have a specialized specialization (generics).

+6
source share
4 answers

Almost the same amount of memory (technically, List is likely to consume even more because it is redistributed so that it can grow easier).

In common .NET collections, there is no need to place the elements that they store, which will be a huge amount of memory and performance.

+10
source

List<T> belongs to the array T[] . It uses an exponential growth strategy for this array, so a list with n elements usually has a swap array with a size larger than n . In addition, smaller arrays must collect garbage, which can be annoying if they are large enough to be on LoH.

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

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


But when using generics, there is no overhead per element. The runtime creates a custom version for each type of value in which you pass. Nothing happens in boxing.

But you cannot use the C ++ style template specialization, where you effectively overload the implementation for certain type parameters. All shared instances have the same C # code.

i.e. there is no specialized IL code, but each type of value receives an implementation of specialized machine code based on the same source code.

+5
source

I ask that since, as far as I know, .NET does not have a specialized specialization (generics).

.Net has no template specialization in the sense that you (as a programmer) can provide different code depending on the type arguments. But the compiler can still (and does) create different code for value types than for a reference type, i.e. (Unlike Java) value types are not boxed when pasted into a shared container. They are effectively stored.

+1
source

Using lists is more practical than using simple arrays. The key to performance and memory consumption is List Capacity. By default, it starts with a value of 4 and increases to 8, 16, 32, 64, ... whenever the list items reach a certain capacity. Each increment is translated into internal redistribution and Array.Copy. Therefore, if you have a list of 1000 items, and you expect 100 items per day, you can create a copy of the list with a capacity of 1200 (the permissible limit in the forecast is 100%). This way you will avoid redistributing for 2000 elements whenever you add an element 10001, and of course continuous redistributions and Array.Copy to fill it with existing 1000 elements.

+1
source

Source: https://habr.com/ru/post/903555/


All Articles