Test the efficiency of the List. ToArray () method.

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.