tags:

views:

190

answers:

3

So in a .NET app , i got about 2 million items that i need to hold them in memory for processing , 1 by 1, would holding these items in a Stack collection , is better than holding them in a List collection, assuming that the memory used by the stack object will be keep minimizing every time an item is poped out of the stack object , or the memory allocated by the stack will keep the same till the stack is set to null, or cleared.

sorry if i couldn't express the question in the right way.. but here is another way, when a Stack collection is used, does the memory used by the stack get minimized every time an item is pulled out of the stack.

Thanks in advance

+4  A: 

They'll basically be the same for Stack<T> if you definitely want FILO behaviour - because when you remove an element from the end of a List<T> it doesn't need to copy anything.

Now if you were talking about a Queue<T> that would be different - removing from the head of a List<T> involves copying the rest of the items, which is inefficient.

The actual memory usage will be the same for either of them - I don't believe either List<T> or Stack<T> automatically "trim to size" when elements are removed.

Jon Skeet
Queue<T> does not trim to size either. It multiplies by the growth factor, which by default is a factor of 4. Strangely, the Queue<t> also has a shrink factor declared, but never used: private const int _ShrinkThreshold = 0x20;
TheSoftwareJedi
+4  A: 

No difference. The "Pop" method of a Stack never reduces the size of the internal array. The "Push" method doubles the size when the limit is hit.

I used .NET Reflector to discover this.

TheSoftwareJedi
+1  A: 

Popping an object out of a stack will remove the reference to the object from the stack. Then, it's up to the garbage collector to decide when to free up the memory. However, depending on the object, you could call .Dispose() after each loop iteration in order to release any unamanged resources the object is using, whcih may or may not be helpful in your case. If you ware working with a class you designed, it can implement IDisposable in order to provide this functionality.

Pop never automatically reduces the amount of memory it has allocated, as another poster pointed out, but it may be forced to do so by calling the Stack's TrimExcess() method. You could call this say every 100 iterations to free up the memory the stack was using. Another nice thing about Stacks is that Pop() is always an O(1) operation.

Another way to reduce memory usage would be to only load, say, 1000 of your objects at a time, then load the next 1000 after iterating through those and repeat until all objects have been loaded.

SoloBold