Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<> Better to init with a maximum capacity and only use a fraction of that, or init with no capacity

Tags:

c#

.net

list

I have a List<MyStruct> that I'm initializing to be empty, and I will be populating this struct in a loop as I parse the data. I know that there is a maximum possible number of entries that will be inserted into this list. For now lets say 1000. However after my parsing of the 1000 entries I may end up only putting 2 into the List. So should I initialize the List with a capacity of 1000 or don't specify a capacity and just add the few entries. It could however end up adding all 1000. What's the best way performance wise?

like image 565
jamone Avatar asked Jan 22 '10 20:01

jamone


1 Answers

Doesn't really matter. Don't micro-optimize. Only set the capacity if you have a good idea it's roughly the amount you need. Under the hood, the list doubles every time it grows, so the number of growths is O(log(n)). It should be pretty efficient.

like image 76
mmx Avatar answered Oct 17 '22 18:10

mmx