My name is Rex Morgan and I'm a Staff Software Engineer in Austin, TX working at Indeed.

I love learning new languages and tinkering with new technologies. I'm currently having fun with Elixir, Java, C#, and Kubernetes.

Performance of Different Types of For Loops

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

This took 1185.8ms to complete.

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

Standard for loop

This took 932.1ms to complete.

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

Optimized for loop

This took 726.1ms to complete.

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