Which is faster: clear collection or instantiate new

后端 未结 8 915
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题