streda 27. júna 2012

For vs. Foreach performance when iterating a generic list

The simplest way is "Test it"!

Performance test:


Code Snippet
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             
  6.             List<int>  list= new List<int>();
  7.             for(int i =0; i < 10000000 ; i++)
  8.             {
  9.                 list.Add(i);
  10.             }
  11.  
  12.             int sum = 0;
  13.             Stopwatch sw = new Stopwatch();
  14.             sw.Start();
  15.             for (int i = 0; i < list.Count; i++)
  16.             {
  17.                 sum += list[i];
  18.             }
  19.  
  20.             sw.Stop();
  21.             Console.WriteLine(" FOR {0}", sw.Elapsed.ToString());
  22.             sw.Reset();
  23.  
  24.             sum = 0;
  25.             sw.Start();            
  26.             foreach (int item in list)
  27.             {
  28.                 sum += item;
  29.             }
  30.             sw.Stop();
  31.             Console.WriteLine(" FOREACH {0}", sw.Elapsed.ToString());
  32.             sw.Reset();
  33.  
  34.             Console.ReadLine();
  35.         }
  36.     }

10 items:
FOR 00:00:00.0000040
FOREACH 00:00:00.0000018

1000 items:
 FOR 00:00:00.0000131
 FOREACH 00:00:00.0000098

100 000 items:
FOR 00:00:00.0010038
FOREACH 00:00:00.0007952

10 000 000 items:
FOR 00:00:00.1031941
FOREACH 00:00:00.0819216

Conclusion:
When you don't need to manipulate items in collection, use Foreach, otherwise For.



Žiadne komentáre:

Zverejnenie komentára