Thursday, 13 December 2012

Which one is the Best Loop Between (For, While, foreach).

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) ;