-3

In this thread we discussed about performance analysis of the for loop and foreach. Which one gives better performance - the for or foreach?

Here are two simple methods:

 public static void TestFor()
{

    Stopwatch stopwatch = Stopwatch.StartNew();
    int[] myInterger = new int[1];
    int total = 0;
    for (int i = 0; i < myInterger.Length; i++)
    {
        total += myInterger[i];
    }
    stopwatch.Stop();
    Console.WriteLine("for loop Time Elapsed={0}", stopwatch.Elapsed);
}
public static void TestForeach()
{
    Stopwatch stopwatchForeach = Stopwatch.StartNew();
    int[] myInterger1 = new int[1];
    int totall = 0;
    foreach (int i in myInterger1)
    {
        totall += i;
    }

    stopwatchForeach.Stop();
    Console.WriteLine("foreach loop Time Elapsed={0}", stopwatchForeach.Elapsed);
}

Then I ran the above code the result was foreach loop Time Elapsed=00:00:00.0000003, for loop Time Elapsed= 00:00:00.0001462. I think we want high performance code. We would use foreach

coder
  • 10,172
  • 17
  • 67
  • 122
Niventh
  • 97
  • 1
  • 7
  • In the for loop you should store `myInteger.Length` outside the `for` statement for better performance. Otherwise it will have to query the array's length for each iteration. – ryan Mar 17 '13 at 14:58
  • Did you call `GC.Collect` between `TestFor` and `TestForeach` invocations? I think the first test can affect the results of second due to garbage collection. – user20140268 Mar 17 '13 at 15:05
  • Any performance test that is not run foe an iteration count that brings the time measurement up to multiple seconds, if not minutes, is suspect. Thee are simply too many possilbe confounds that might add a few spurious tenths of a second, to believe any performance test running less than about 5 seconds overall. – Pieter Geerkens Mar 17 '13 at 16:09
  • Thanks to all.......... – Niventh Mar 18 '13 at 14:42

1 Answers1

1

My decision would not be based on some simple performance loop like this. I am assuming that you have a frequent use of loops/large data sets. You will not notice the difference until we start talking about iterations in the hundreds of thousands (at a minimum).

1) If you are writing applications with potential memory pressured frameworks (XBOX, Windows Phone, Silverlight). I would use the for loop as foreach can leave lightweight "garbage" that can be left behind for collectioning. When I was doing XBOX development years ago for games, a common trick was to initialize a fixed array of items shown on a screen using a for loop and keep that in memory and then you don't have to worry about garbage collection/memory adjustments/garbage collection etc. This can be an issue if you have a loop like this called 60+ times/second (i.e. games)

2) If you have a very large set you are iterating AND performance is your key decision driver (remember these numbers are not going to be noticeable unless they are large), then you may want to look at parallelizing your code. The difference then might not be for vs foreach, but Parallel.For vs Parallel.Foreach vs PLINQ (AsParallel() method). You have have different threads tackle the problem.

Edit: In a production application, you are more than likely going to have some kind of logic in your loops which will take >>> time to iterate an item. Once you add that to the mix performance drivers usually shift to the actual logic not optimizing iterations (which the compiler does pretty well).

Bart Czernicki
  • 3,508
  • 1
  • 17
  • 16
  • 1
    hundreds of thousands of iterations are unlikely to be enough of an overhead to be noticeable. You'd probably need to be iterating tens or hundreds of millions, if not billions, of times to really notice the difference. – Servy Mar 18 '13 at 15:57