Which is faster: clear collection or instantiate new

Mrimsh picture Mrimsh · Jun 5, 2012 · Viewed 32.4k times · Source

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 faster, to call Clear() method or creating a new List<T>()?

Answer

Reed Copsey picture Reed Copsey · Jun 5, 2012

what will be faster, to call Clear() method or creating a `new List()?

This is impossible to answer. It really depends on a lot of factors, including how long the collection has existed.

The best option here would be to:

  1. Profile the application, and see if this really matters. It likely won't make any perceptible difference, in which case, I'd use the method that makes the most sense in terms of how you think of this object.

  2. If it does matter, write both sets of code, and measure the difference in speed (if any).

From a practical perspective, calling Clear() will not actually reduce the memory (used by the List<T> itself), as it doesn't shrink the list's capacity, only eliminates the values contained within it. Creating a new List<T> will cause a new list to be allocated, which will in turn cause more allocations with growth.

This, however, does not mean that it will be slower - in many cases, reallocating will be faster as you're less likely to promote the large arrays into higher garbage collection generations, which in turn can keep the GC process much faster.

Without knowing your exact scenario and measuring in a profiler, there is no way to know which is better in your scenario.