.net - Which is faster: clear collection or instantiate new -


i have number of generic lists in code, have tens or hundreds elements. need refill lists other objects, question is: faster, call clear() method or creating new list<t>()?

what faster, call clear() method or creating new list()?

this impossible answer. depends on lot of factors, including how long collection has existed.

the best option here to:

  1. profile application, , see if matters. won't make perceptible difference, in case, i'd use method makes sense in terms of how think of object.

  2. if matter, write both sets of code, , measure difference in speed (if any).

from practical perspective, calling clear() not reduce memory (used list<t> itself), doesn't shrink list's capacity, eliminates values contained within it. creating new list<t> cause new list allocated, in turn cause more allocations growth. this, however, not mean slower - in many cases, reallocating faster you're less promote large arrays higher garbage collection generations, in turn can keep gc process faster. without knowing exact scenario , measuring in profiler, there no way know better in scenario.


Comments