Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Within C# is a loop declaration evaluated each time?

This is a really nit-picky question, but curiosity got the better of me.

Does a for loop re-evaluate the RHS condition each time the loop executes? See below.

for(int i = 0; i < collection.Count; i++)
{
}

Is it good practice throughout your code base to do the following?

for(int i = 0, n = collections.Count; i < n; i++)
{
}

Or does the compiler do these kind of optimisations / they're negligible (even with a huge code base)?

like image 372
user3585831 Avatar asked Apr 21 '26 12:04

user3585831


1 Answers

The condition will be reevaluated before every iteration (unless the compiler detects that the condition is constant), and it is acceptable to write code that depends on this (such as calling a function whose return value will be different each time). Thus, if you have a condition that is expensive to evaluate and you are sure it will remain constant, it is indeed a good idea to evaluate it once, before the loop. However, for most standard collection types, Count is such a fast operation that the negligible performance gain won't be worth the reduced readability.

like image 155
Aasmund Eldhuset Avatar answered Apr 24 '26 04:04

Aasmund Eldhuset



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!