Using Stack <T> is better than List <T> in terms of memory usage with .NET.

So, in a .NET application, I have about 2 million items that I need to hold in memory for processing, 1 to 1, holding these items in the Stack collection is better than holding them in the List collection, assuming the memory used by the object of the stack, will decrease each time an item is unloaded from the stack object, or the memory allocated by the stack will support the same until the stack is set to zero or cleared.

Sorry if I couldn’t express the question correctly. But here is another way, when the Stack collection is used, whether its own memory used by the stack allows each time an item is pulled from the stack.

Thanks in advance

+3
source share
3 answers

No difference. The Pop method of the stack never reduces the size of the internal array. The Push method doubles the size when the limit is reached.

I used the .NET Reflector to detect this.

+4
source

Basically they will be the same for Stack<T>if you definitely want the FILO behavior - because when you remove an element from the end List<T>, it doesn't need to copy anything.

Now, if you were talking about Queue<T>, which would be different - removing from the header List<T>means copying the rest of the elements, which is inefficient.

- , List<T> Stack<T> " " .

+4

. , , , . , , .Dispose() , , , . , , IDisposable, .

Pop never automatically reduces the amount of allocated memory, as another poster pointed out, but this can be forcibly done by calling Stack TrimExcess () . You can call it every 100 iterations to free up the memory that the stack used. Another nice thing about Stacks is that Pop () is always an O (1) operation.

Another way to reduce memory usage is to just load, say, 1000 of your objects at a time, and then load the next 1000 after iterating through them and repeating until all objects are loaded.

+1
source

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


All Articles