C #: How fast is the Clear method of Array ???

Source: Internet
Author: User

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.

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.