C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Or should you just allocate a new List? My intuition was that clearing and reusing an existing list would result in better performance. But I found the opposite was true.
Example. This benchmark tests two methods. The first, Method1, calls Clear on an existing List and then adds 100 ints to it. Method2 instead changes the reference to point to a new List with capacity of 100.
Tip: Both methods have the same result, which is a list of 100 integers from 0 to 99. Method1 requires a non-null reference.
Input list: C# // ... New list. var list = new List<int>(100); Method 1, Clear List: C# static List<int> Method1(List<int> list) { // ... Clear same list, then add 100 ints. list.Clear(); for (int i = 0; i < 100; i++) { list.Add(i); } return list; } Method 2, New List: C# static List<int> Method2(List<int> list) { // ... New list, then add 100 ints. list = new List<int>(100); for (int i = 0; i < 100; i++) { list.Add(i); } return list; } Benchmark results 645.81 ns Clear 501.57 ns New List
In the results, calling Clear() on the List was slower. It is faster to simply allocate a new List rather than clear an existing List. This depends on how fast the Clear() method is versus the speed of the memory allocation.
Discussion. This test depends on many factors. The version of the method that reuses the same List, Method1, will cause less churn in the garbage collector. But it has an additional cost of the Clear method.
Also, the size of the list and its underlying array will play a part. A large List would cause different parts of the garbage collection system to be used. It could even be considered a large object, and treated separately in memory.
However: Avoiding new collection allocations is not a reliable optimization. Simply creating a new List when one is needed is best.
Summary. We tested the List Clear method. In some cases, using a new List to replace the old List is faster. This depends on the relative performance of the managed heap. Other program characteristics (overall memory use) also affect this.