O'Reilly logo

ASP.NET Site Performance Secrets by Matt Perdeck

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Foreach

The C# statement foreach is a convenient way to traverse an enumerable collection, but because it uses an enumerator it is also more expensive than a normal for loop.

The following code uses a trivial foreach loop:

int k = 0;
foreach loopforeach (int j in list)
{
k = j;
}

This code uses a for loop instead:

int k = 0;
int listLength = list.Count;
for (int i = 0; i < listLength; i++)
{
k = list[i];
}

For completeness, I also tested a loop that counts backwards to zero, rather than forwards to the list count:

int k = 0;
for (int i = list.Count - 1; i >= 0; i--)
{
k = list[i];
}

I used a List<int> with 1000 integers. On my machine, the results were:

Test

Time taken (ticks)

foreach—1000 List<int> accesses

168

for 1000—List<int> accesses

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required