New Collection vs. Collection.Clear

320 words

Quick, which one of the following implementations is faster to use in a time-critical section of code:

Implementation 1:

   25 for( int i = ; i < iterations; i++ )

   26 {

   27     List<int> myList = new List<int>();

   28     for( int j = ; j < 1000; j++ ) myList.Add( j );

   29 }

Implementation 2:

   34 List<int> myList = new List<int>();

   35 for( int i = ; i < iterations; i++ )

   36 {

   37     myList.Clear();

   38     for( int j = ; j < 1000; j++ ) myList.Add( j );

   39 }

Answer:  The second one, by about 33%.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Diagnostics;

    4 using System.Text;

    5 

    6 namespace CollectionSpeedTest

    7 {

    8     class Program

    9     {

   10         static void Main( string[] args )

   11         {

   12             long time1 = Stopwatch.GetTimestamp();

   13             Method1( 1000000 );

   14             long time2 = Stopwatch.GetTimestamp();

   15             Method2( 1000000 );

   16             long time3 = Stopwatch.GetTimestamp();

   17 

   18             Console.WriteLine( "Method1: {0}", time2 - time1 );

   19             Console.WriteLine( "Method2: {0}", time3 - time2 );

   20             Console.ReadLine();

   21         }

   22 

   23         public static void Method1( int iterations )

   24         {

   25             for( int i = ; i < iterations; i++ )

   26             {

   27                 List<int> myList = new List<int>();

   28                 for( int j = ; j < 1000; j++ ) myList.Add( j );

   29             }

   30         }

   31 

   32         public static void Method2( int iterations )

   33         {

   34             List<int> myList = new List<int>();

   35             for( int i = ; i < iterations; i++ )

   36             {

   37                 myList.Clear();

   38                 for( int j = ; j < 1000; j++ ) myList.Add( j );

   39             }

   40         }

   41     }

   42 }

Results:

Method1: 20962096146

Method2: 13987606779

Originally posted on my personal blog which was active from 2003 to 2020.

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.