From msdn, we know that the time complexity of the Clear method of Array is O (n ).
Today, let's test whether this method is fast or self-compiled:
Is Clear () fast, or directly new an object is fast.
Program viewing
private void Experiment() { System.Diagnostics.Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); string[] aa = new string[10000]; for (var loop = 0; loop < 100000; loop++) { // string[] aa = new string[10000]; for (var i = 0; i < 10000; i++) { aa[i] = "a"; } //Array.Clear(aa, 0, 10000); for (var i = 0; i < 10000;i++ ) { aa[i] = null; } } stopwatch.Stop(); Console.WriteLine("All timeL:"+stopwatch.Elapsed.TotalSeconds); }
After comparison, the following data is obtained:
Compared with the new object solution, Clear () takes 5.7 seconds. The latter takes 6.3 s
For comparison between Clear () and Self-compiled Traversal Algorithms, the former is 5.7 s, and the latter is 8.5 s.
The basic condition for this data is the time for executing 10000 statistics on an array with a length of 0.1 million.
Obviously. It doesn't matter if you need to execute it once.
If you need to write the code multiple times, it is better to write the code carefully.