Performace using foreach

  • Thread starter Thread starter mortb
  • Start date Start date
M

mortb

Is there any gain in preformace using

for(int i=0; i < fooList.Count; i++)
{
doStuffTo(foo);
}

Compared to

foreach(fooObj oFoo in fooList)
{
doStuffTo(oFoo);
}

...and what about comparing arrays to arrayLists

Just curious
greetings,
mortb
 
I don't know about the performance, but the readability is far better
using foreach.
 
There are some instances where foreach is actually faster than a for loop
because the
enumerator performs better than the indexer into the collection. I highly
recommend
performance tuning your application to find out what works better, and if you
need to
modify the collection during an iteration or you need to be able to skip
elements then
you'll use the for loop instead of the foreach.
 
I realize this is not a direct answer, but still - I'd check the doStuffTo()
performance first. Loop overheads DO count, but only when they are of the
same magnitude as the loop body itsellf in terms of consumed CPU time.

Closer to the real word - aggressive loop optimisation is usually reasonable
only in time-critical applications such as 3D action games, and only after
the loop has been identified as a bottleneck with a profiling tool.
 
Back
Top