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];
}
July 14th, 2007 at 12:11 pm
m-curlz would be proud!
July 24th, 2007 at 12:44 am
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.
October 22nd, 2007 at 8:21 am
Hey, HEY YOU.
BLOG MORE.
October 25th, 2007 at 9:31 pm
OMG how did I get here? Im so lost.
Last post was in JULY?!!