C # Performance Analysis-specify the set capacity

Source: Internet
Author: User

Collection classes with dynamically increased length, such as ArrayList and Queue, do not need to specify their capacity during initialization. The set itself can automatically increase the set size as needed, making it easy for programming. However, over-reliance on this feature is not a good choice for improving program performance, because the process of dynamically adding a set is a process of memory reallocation and copying set elements, it will have a certain impact on the performance, so it is necessary to specify an appropriate capacity during the collection initialization.

The following three cases are used to test the effect of the specified set capacity on program performance.

 

Test code
 1 using System;
2 using System. Collections. Generic;
3 using System. Text;
4 using System. Collections;
5
6 namespace Test_Console
7 {
8 class Program
9 {
10 static void Main (string [] args)
11 {
12 TimeSpan ts = new TimeSpan ();
13 DateTime dt = DateTime. Now;
14
15 // Case 1: do not specify the length of the array
16
17 for (int I = 0; I <100000; I ++)
18 {
19 ArrayList al = new ArrayList ();
20 al. Add ("one ");
21 al. Add ("two ");
22 al. Add ("three ");
23 al. Add ("four ");
24 al. Add ("five ");
25}
26
27 ts = DateTime. Now. Subtract (dt );
28 Console. WriteLine (ts. Milliseconds + "millisecond ");
29
30 dt = DateTime. Now;
31
32 // Case 2: specify the appropriate capacity for the collection object during initialization
33
34 for (int I = 0; I <100000
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.