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?
I have a List<MyStruct> that I’m initializing to be empty, and I will be
Share
If it can truly vary that widely, then you would want to not set the capacity. For most collections, the capacity doubles as it is met (with a default capacity of 16 I believe), so your capacity will very closely approach your maximum as you fill it up.