+ 10

Clear() collection VS instantiate new List<T>

I have some number of generic lists in my code. And in most cases i need to refill this lists with other objects, so question is: which one is faster, call Clear() method or creating a new List<T>()? And which one have the best Performance at freeing up memory (Garbage Collection)

4th Feb 2020, 8:00 AM
hossein B
hossein B - avatar
2 Respuestas
+ 7
Clear() method is a usual way, but in totally if you use so many list<>s it's better to create new list and change the name of it.
18th Feb 2020, 5:09 PM
P. T
P. T - avatar
+ 3
In terms of performance, Clear() is faster for smaller lists containing fewer objects, and initialisation is faster for larger lists. In terms of memory allocation, initialisation is more efficient. When you call Clear(), the size of the list goes back to 0, but its internal array remains at the same length as before. This is because it estimates that you will fill it with roughly the same amount of objects. It does improve performance when calling Add() on the list, afterwards, since it doesn't need to initialise a new array at each insertion (until the array length is reached). In terms of general programming, I would personally use Clear() for no other reason than it's more readable and intuitive. Typically, you wouldn't need to even care about the performance/memory impact unless you're working with tens of thousands of complex objects, in a large database where every millisecond and byte counts: it's a small difference.
4th Feb 2020, 2:53 PM
Soapenhauer
Soapenhauer - avatar