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.
The above section describes the List. toArray () method efficiency test, hope to help you, if you have any questions, please leave a message, xiaobian will reply to you in a timely manner. Thank you very much for your support for the help House website!