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.
[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 )
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) ;
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.
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:
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).
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.
sun21170
Contributor
3421 Points
1189 Posts
Which loop is better in performance - foreach or for or while?
Nov 01, 2006 08:06 PM|LINK
budugu
All-Star
41132 Points
6021 Posts
Re: Which loop is better in performance - foreach or for or while?
Nov 01, 2006 08:24 PM|LINK
[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 )
"Don't be afraid to be wrong; otherwise you'll never be right."
vcsjones
All-Star
34842 Points
4424 Posts
Moderator
MVP
Re: Which loop is better in performance - foreach or for or while?
Nov 01, 2006 08:25 PM|LINK
sun21170
Contributor
3421 Points
1189 Posts
Re: Which loop is better in performance - foreach or for or while?
Nov 01, 2006 08:45 PM|LINK
vcsjones
All-Star
34842 Points
4424 Posts
Moderator
MVP
Re: Which loop is better in performance - foreach or for or while?
Nov 02, 2006 02:29 AM|LINK
It varies. "while" and "for" have pretty much the same results. While had a slight advantage, but not one that great.
shados
Star
12285 Points
2229 Posts
Re: Which loop is better in performance - foreach or for or while?
Nov 02, 2006 02:34 AM|LINK
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.
vcsjones
All-Star
34842 Points
4424 Posts
Moderator
MVP
Re: Which loop is better in performance - foreach or for or while?
Nov 02, 2006 04:45 AM|LINK
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:
And here it is for the while loop:
So yes, they are exactly identical.shados
Star
12285 Points
2229 Posts
Re: Which loop is better in performance - foreach or for or while?
Nov 02, 2006 05:33 AM|LINK
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).
Alan Ourslan...
Member
187 Points
29 Posts
Re: Which loop is better in performance - foreach or for or while?
Nov 02, 2006 04:57 PM|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:
vcsjones
All-Star
34842 Points
4424 Posts
Moderator
MVP
Re: Which loop is better in performance - foreach or for or while?
Nov 02, 2006 05:00 PM|LINK