Here is a simple question I have been wondering about for a long time : When I do a loop such as this one :
for (int i = 0; i < myVector.size() ; ++i) {
// my loop
}
As the condition i < myVector.size() is checked each time, should I store the size of the array inside a variable before the loop to prevent the call to size() each iteration ? Or is the compiler smart enough to do it itself ?
mySize = myVector.size();
for (int i = 0; i < mySize ; ++i) {
// my loop
}
And I would extend the question with a more complex condition such as i < myVector.front()/myVector.size()
Edit : I don't use myVector inside the loop, it is juste here to give the ending condition. And what about the more complex condition ?
myVector.front()/myVector.size()is a constant expression (provided you do not modify the vector inside the loop). Ayway that's a matter of optimization, and results may differ between compiler versions and optimization modes. So I won't tell you whether you should calculate the terminating value before the loop or not; just compile your code to assembler source and see if the compiler produces the full calculations on each iteration. If so, then optimizing by yourself may make sense.