To prevent many re-allocations I have something like this in my code:
List<T> result = new List<T>(100);
Do I need to call TrimExcess before I return the new list or not?
result.TrimExcess();
return result;
The aim is to make the allocations quicker for the first 100 items, for example. Is this the correct way of doing this or do I need to do anything else?
By defining the initail capacity, you did the necessary optimization.
If you the call the
TrimExcess()method you might cause more allocation work than you really want.The MSDN documentation for
TrimExcess()says:What I understand of this is that you might not even change anything on your list with that call.
This looks to me that you really do not gain much with it.