Home
C#
List Clear Example
This page was last reviewed on Sep 1, 2023.
Dot Net Perls
List, Clear. Should you clear a List to reuse it, or should you just allocate a new List? We test whether the Clear() method helps improve code that uses List.
Shows a list
Performance info. It seems likely that clearing and reusing an existing list would result in better performance. This hypothesis can be tested.
List
Array.Clear
Example. Here we create a List, and call Add() twice to append 2 elements to the List. The List has 2 elements at that point. We call Clear(), and then it has 0 elements.Shows a list
using System; using System.Collections.Generic; List<int> ids = new List<int>(); ids.Add(10); ids.Add(11); Console.WriteLine("COUNT: {0}", ids.Count); // Do not assign anything to clear. ids.Clear(); Console.WriteLine("COUNT: {0}", ids.Count);
COUNT: 2 COUNT: 0
Benchmark, clear. All code that uses a List must first allocate it, or clear an existing List to reuse that one. Consider this benchmark program. The program tests 2 methods.
Version 1 This code calls Clear on an existing List and then adds 100 ints to it.
Version 2 This code instead changes the reference to point to a new List with capacity of 100.
List Capacity
Result In 2021 with .NET 5 for the Linux operating system, using Clear() on an existing List is faster.
using System; using System.Collections.Generic; using System.Diagnostics; const int _max = 1000000; // ... New list. var list = new List<int>(100); // Version 1: clear 1 list and reuse it many times. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { list.Clear(); for (int x = 0; x < 100; x++) { list.Add(x); } } s1.Stop(); // Version 2: create a new list on each use. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { list = new List<int>(100); for (int x = 0; x < 100; x++) { list.Add(x); } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
156.06 ns List Clear 182.58 ns new List
Notes, results. In the results, calling Clear() on the List was faster. The Array.Clear method has undergone performance optimizations.
Info This depends on how fast the Clear() method is versus the speed of the memory allocation.
Important Avoiding new collection allocations is often a good optimization. But this should always be tested.
A summary. We tested the List Clear method. This method clears the List's contents and adjusts the Count to zero after it is called.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 1, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.