Performance of Different Types of For Loops

Posted on 13. July 2007

In an old post I found online the author asks how you would go about writing a simple for loop. I was bored tonight, so I wrote a simple program to time several different types of loops to confirm which is the fastest at iterating through a generic list, yes… that bored. My list contained 67,108,863 integers.

Here are the results:

Foreach loop: 1185.8ms

int tmp;
foreach (int i in array)
{
    tmp = i;
}

Standard for loop: 932.1ms

int tmp;
for (int i = 0; i < array.Count; i++)
{
    tmp = array[i];
}

Optimized for loop: 726.1ms

int tmp;
int cnt = array.Count;
for (int i = 0; i < cnt; ++i)
{
    tmp = array[i];
}