Performance of Different Types of For Loops

C#, Programming Add comments

In an old post I found online here 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];
}

4 Responses to “Performance of Different Types of For Loops”

  1. codePoet Says:

    m-curlz would be proud!

  2. ryan Says:

    You’re this bored and this is the best you can do?

    Did you take into account that in your optimized loop you have the count set as a variable, where in your standard loop you have to calculate it every single time? That would have been a nice intermediary step.

    Next see how long it takes if you just hard code it.

  3. Josh Says:

    Hey, HEY YOU.

    BLOG MORE.

  4. Jason Says:

    OMG how did I get here? Im so lost.

    Last post was in JULY?!!

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in