Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List<> should I lower capacity as I remove items?

Tags:

c#

list

capacity

I have a List container which can potentially have up to 100,000 items in to start with. While the program is running this list will slowly empty, should I alter the capacity as I empty the list?

I have done some testing and execution time seems to be the same, but is there much overhead to lowering the capacity of a list? I can find lots of information about increasing the capacity but not much on lowering it.

like image 918
Eddie Avatar asked Aug 23 '11 14:08

Eddie


2 Answers

Unless you have a very low amount of memory, this is a micro-optimization.

Normally, there is no need to change the capacity of a List<>.

From the TrimExcess method documentation:

This method can be used to minimize a collection's memory overhead if no new elements will be added to the collection. The cost of reallocating and copying a large List<T> can be considerable, however, so the TrimExcess method does nothing if the list is at more than 90 percent of capacity. This avoids incurring a large reallocation cost for a relatively small gain.

like image 98
Oded Avatar answered Sep 23 '22 23:09

Oded


Do the math: 100,000 items * 4 bytes per item = roughtly 400KB. If that's too much memory overhead for your program, you can call TrimExcess, as Oded points out recreate smaller lists once it gets smaller. (I'm not sure that reducing the capacity will actually have the effect you're going for.)

like image 26
StriplingWarrior Avatar answered Sep 19 '22 23:09

StriplingWarrior