ForEach vs For for optimization

  • Thread starter Thread starter Katie
  • Start date Start date
K

Katie

i know foreach is faster than for when working with objects. however, for is
more flexible than foreach. you can step through a for statement in reverse
order and even skip items. so.... is there a way to iterate thru the items
in revers order with a foreach statement? i know this is a general
programming question but i always like to optimize my PocketPC code. this
would be another optimization... that is being able to use foreach when i
need to iterate in reverse order vs using a for statement.

so is there a way to iterate thru a foreach in revers order?

thanks
 
Katie,

Not that I can think of without filling the items in a collection in reverse
order in the first place. Just use for.
 
Katie said:
i know foreach is faster than for when working with objects. however, for is
more flexible than foreach. you can step through a for statement in reverse
order and even skip items.

Yikes - I never mess with a for loop's variable. If I need to do that, I
use a while loop. Who knows what the compiler is doing to the for loop, I'm
not messing with it - loop unrolling etc etc.

Anyone want to comment if messing with a for loop's variable is safe (in
C#)?

Hilton
 
I personally don't do it for many reasons, but I have a co-worker that does
it extensively and has never had any problems. At best I think it hurts
readability and at worse it can lead to serious logic flaws. However, I do
know of two .NET programs that employ it all over the place and haven't had
any problems (that we know of)
 
Back
Top