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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With