Which is faster: clear collection or instantiate new

后端 未结 8 872
遇见更好的自我
遇见更好的自我 2020-12-01 06:26

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

相关标签:
8条回答
  • 2020-12-01 06:46

    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.

    0 讨论(0)
  • 2020-12-01 06:48

    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.

    0 讨论(0)
提交回复
热议问题