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