Test the efficiency of the List. ToArray () method.
Previously, I always thought that because the internal implementation of List is an array, the implementation of ToArray only returns the array.
I tested it today and found that it wasn't that.
Var a = new List <int> (); for (int I = 0; I <10000; I ++) {. add (I);} DebugHelper. startWatch (); foreach (var I in Enumerable. range (0, 10000) {. toArray ();} DebugHelper. stopWatch ();
For a List with a size of 10 thousand, the time consumed for calling 10 thousand ToArray is about milliseconds.
I read the source code and did not expect it to copy the internal array before returning it.
Public T [] ToArray () {T [] array = new T [this. _ size]; Array. copy (this. _ items, 0, array, 0, this. _ size); return array ;}
It seems that for repetitive operations, you can directly cache them as global variables or directly use List as parameters.