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?
r开发者_如何学Cesult.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?
You do not need to trim. The list keeps track of how many items have actually been added, which is different than the initial capacity, which is simply a pre-allocation.
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:
The cost of reallocating and copying a large List can be considerable, however, so the TrimExcess method does nothing if the list is at more than 90 percent of capacity
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.
its ok ..
if you dont intend to add more items then you can leave it like you wrote.
If your application is using a lot of memory or more than it should then I would call TrimExcess() but it's probably not worth it unless the list contains very little items like less than 30 or so, even then you probably can just leave it as is. But yes if you want allocation to be faster for the first 100 then make the initial size 100 or even larger if you know you're going to be adding more than 100 items.
Let's make it clear, doing so will not reserve memory for allocation of 100 T but just for 100 'pointer' to T. So it is ok but probably does not help a lot.
精彩评论