Performance of Different Types of For Loops

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];
}
This entry was posted in C#, Programming and tagged , , , , , . Bookmark the permalink.

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

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>