I have some number of generic lists in my code, that have tens or hundreds elements. Sometimes I need to refill this lists with other objects, so question is: what will be f
Clear()
will remove all elements, and maintain the existing capacity, whereas creating a new List will need at least one allocation from the managed heap (possibly more as items are added if the initial capacity is small).
If you have a large number of items, and the number of items is roughly the same on each iteration, then using Clear
is potentially slightly faster.
If you have an exceptionally large number of items on one iteration, then a much smaller number on subsequent iterations, then using Clear
is potentially more costly, because you'll be keeping in memory a list with an unnecessarily large capacity.
Of course, in many (most?) scenarios the difference will be negligible.