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
While this may be frustrating, the answer really is that it shouldn't matter. The time difference between the two is going to be so small that it probably won't make any difference to your application. Do what leads to cleaner, more understandable code, and try not to program for micro-optimizations.
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.