# Which loop is better in performance - foreach or for or while? [Answered]RSS

## 15 replies

Last post Nov 08, 2006 10:02 PM by shados

Member

123 Points

1244 Posts

### Which loop is better in performance - foreach or for or while?

I was curious about which looping technique is considered best in performance among foreach, for and while? I know we can optimize speed of our code using the right looping technique.
sun21170

All-Star

29295 Points

5969 Posts

### Re: Which loop is better in performance - foreach or for or while?

[quote user="sun21170"]I was curious about which looping technique is considered best in performance among foreach, for and while? I know we can optimize speed of our code using the right looping technique.

For is better in performance. ( experts, correct me if i am wrong )

Vijay Kodali || My Blog

"Don't be afraid to be wrong; otherwise you'll never be right."

All-Star

24869 Points

4372 Posts

Moderator

MVP

### Re: Which loop is better in performance - foreach or for or while?

That is always open to debate. Using the System.Diagnostics.Stopwatch class I ran some tests. 100,000 iterations in a for loop that did nothing inside took me 0.0003745 seconds. This was the code for the loop:
`for (int i = 0; i < 100000; i++) ;`
The while loop resulted 0.0003641 seconds, which is pretty much the same as the for loop. Here is the code I used:
```int i=0;
while (i < 100000)
i++;```
The foreach loop has a slightly different purpose. It is meant for itterating through some collection that implements IEnumerable. It's performance is much slower, my test resulted in 0.0009076 seconds with this code:
```int[] test = new int[100000];
foreach (int i in test) ;```
Hopefully that clears it up a bit for you.

Member

123 Points

1244 Posts

### Re: Which loop is better in performance - foreach or for or while?

So, it seems that 'while' is the fastest looping technique among the three available techniques in C#,  for a given processing within the loop. Right?
sun21170

All-Star

24869 Points

4372 Posts

Moderator

MVP

### Re: Which loop is better in performance - foreach or for or while?

It varies. "while" and "for" have pretty much the same results. While had a slight advantage, but not one that great.

Contributor

7220 Points

2216 Posts

### Re: Which loop is better in performance - foreach or for or while?

Im not an expert, but I have the feeling that a while and for loop, once compiled to MSLI, probably are both the exact same thing.

And I wouldn't be surprised if foreach was faster when iterating through objects, since the optimizer can "expect" whats going to happen... So I'd go with foreach being faster if you can use it, and the 2 others being the same thing, if foreach isn't applicable.

My logic here is that if you're looping through a collection, and you use a for loop for example, you're going to have to use the index of the collection, which depending on implementation, could be a minor performance hit to "seek" the object, as opposed to going through a well written iterator. Just an example.

So really: I wouldn't care too much about performance of these loops. This isn't C/C++, and when you compile, its not native code (at first). So it is safe to assume that the solution that seems the most efficient "logically" will be so in practice.

All-Star

24869 Points

4372 Posts

Moderator

MVP

### Re: Which loop is better in performance - foreach or for or while?

For each is slower for a number of reasons. One is it is using the IEnumerable interface, which requires some casting (assuming you aren't using a generic collection). My test above seemed to go along with that as well. A simple for/while/do loop is pretty much as simple as it gets.

As for the MSIL code, let's take a look. This is the MSIL for the for loop:

``` IL_0000:  nop
IL_0001:  ldc.i4.0
IL_0002:  stloc.0
IL_0003:  br.s       IL_0009
IL_0005:  ldloc.0
IL_0006:  ldc.i4.1
IL_0008:  stloc.0
IL_0009:  ldloc.0
IL_000a:  ldc.i4     0x186a0
IL_000f:  clt
IL_0011:  stloc.1
IL_0012:  ldloc.1
IL_0013:  brtrue.s   IL_0005
```

And here it is for the while loop:

```  IL_0000:  nop
IL_0001:  ldc.i4.0
IL_0002:  stloc.0
IL_0003:  br.s       IL_0009
IL_0005:  ldloc.0
IL_0006:  ldc.i4.1
IL_0008:  stloc.0
IL_0009:  ldloc.0
IL_000a:  ldc.i4     0x186a0
IL_000f:  clt
IL_0011:  stloc.1
IL_0012:  ldloc.1
IL_0013:  brtrue.s   IL_0005
```

So yes, they are exactly identical.

Contributor

7220 Points

2216 Posts

### Re: Which loop is better in performance - foreach or for or while?

Nice to see I was right about the byte code.

For the foreach, I guess you're right, I didn't think about casting issues. One thing though, to be a fair comparison, you'd have to fetch something in your for and while loops... like:

while( i <...
test2 = test[i]

or something. Because just looping through, as opposed to looping + seeking, thats kind of a difference. You're right, foreach probably lags behind, but in that scenario, it was doing a bit more (albeit not much).

Member

90 Points

29 Posts

### Re: Which loop is better in performance - foreach or for or while?

Nov 02, 2006 04:57 PM|Alan Oursland|LINK

I ran a quick test:

```int[] a = range(0, 100000000);

DateTime time0 = DateTime.Now;
long sum = 0;
int i = 0;
while( i < a.Length ) {
sum += a[i];
i++;
}

DateTime time1 = DateTime.Now;
sum = 0;
foreach( int ai in a ) {
sum = ai;
}
DateTime time2 = DateTime.Now;

System.Console.WriteLine(time1.Subtract(time0).TotalMilliseconds);
System.Console.WriteLine(time2.Subtract(time1).TotalMilliseconds);```

Results in:

```281.2464
218.7472```
`foreach creates an Enumerator object and calls MoveNext a bunch of times. If you can traverse the list faster that that iterator can, then use your customer loop. Otherwise, use whatever you find easiest to write and trust the compiler to do it as quickly as possible.`

All-Star

24869 Points

4372 Posts

Moderator

MVP

### Re: Which loop is better in performance - foreach or for or while?

DateTime is a very poor measurement for diagnostics. I recommend using System.Diagnostics.Stopwatch for accurate results.

All-Star

24869 Points

4372 Posts

Moderator

MVP

### Re: Which loop is better in performance - foreach or for or while?

Using the stop watch, and making sure the loops are both doing the same thing, using the for loop:

```int[] ints = new int[100000];
int j;
for (int i = 0; i < 100000; i++)
{
j = ints[i];
}```
That took 0.0011128 seconds (an average of 3 tests). Using the foreach loop:
```int[] ints = new int[100000];
int j;
foreach(int i in ints)
{
j = i;
}```
That took an average of 0.0013745 seconds. They are close, but the for loop had better performace. However, I am sure there are situations where a foreach statement will have better performance. But for a simple array, a for loop peformed better, though only slightly.

Member

90 Points

29 Posts

### Re: Which loop is better in performance - foreach or for or while?

Nov 02, 2006 11:29 PM|Alan Oursland|LINK

> DateTime is a very poor measurement for diagnostics. I recommend using System.Diagnostics.Stopwatch for accurate results.

That is very useful. Thank you.

Contributor

3938 Points

3296 Posts

### Re: Which loop is better in performance - foreach or for or while?

Honestly the academically correct answer is "It's Irrelevant".  You cant optimize performance by somehow picking "the best loop".  If you're doing performance optimizations you should start with a Big O analysis of your algorithms and Profiling.  You'd be amazed at how much faster keeping around a dictionary for lookups or using a sorted list + binary search is than looping over a list every time you need to find an object.

Warning: Code is often uncompiled and possibly started life written on the back of a napkin. Beware typos.

Contributor

7220 Points

2216 Posts

### Re: Which loop is better in performance - foreach or for or while?

You can :) Even after your algorythm is perfect, there are still things at the machine level which matters. For example in certain languages that have 2 dimentional arrays, often, the runtime is optimized for 1 dimention arrays, so doing an array of arrays, is faster than doing a 2 dimentional array (even though for your algorythm, it doesn't matter at all). Back in the good old days (well, its good old days to me, even though some people still use them...a lot even!) of raw C/C++ compiled to native, the order in which you did your loops mattered greatly, again: even though it was irrelevent to the algorythm.

Behind all the theory (which, admitedly, matters more than all of this), there is still a machine made of metal and silicons, and systems on which you have no control, and the way they work does matter.

Contributor

3938 Points

3296 Posts

### Re: Which loop is better in performance - foreach or for or while?

True, my point however is that 99.999% of the time in the .Net world you're never going to that level of optimization is nothing more than intelectual masturbation.  Doing so will give you unnoticable performance increases at the cost of maintainability and programmer time and the effort you're putting in to such small performance boosts is better spent on a proper design and implementation.   Let's take a real world example of finding duplicates in a list to illustrate my point:

first let's assume that comparing two items is O(1).  We can implement this any number of ways, two of which are:

A) use nested loops with i on the outer loop and j on the inner loop, when list[i] == list[j] push the pair onto a list of duplicates.

B) copy the list to tmpList.  quicksort tmpList.  iterate over the list with i, when list[i] == list[i+1] push the pair onto the list of duplicates

No amount of optimization can change the fact that A runs in O(n^2) while B runs in O(2*n+n*log(n)).

Warning: Code is often uncompiled and possibly started life written on the back of a napkin. Beware typos.

Contributor

7220 Points

2216 Posts