Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ for loop optimization question

I have the following looking code in VC++:

for (int i = (a - 1) * b; i < a * b && i < someObject->someFunction(); i++)
{
    // ...
}

As far as I know compilers optimize all these arithmetic operations and they won't be executed on each loop, but I'm not sure if they can tell that the function above also returns the same value each time and it doesn't need to be called each time.

Is it a better practice to save all calculations into variables, or just rely on compiler optimizations to have a more readable code?

int start = (a - 1) * b;
int expra = a * b;
int exprb = someObject->someFunction();
for (int i = startl i < expra && i < exprb; i++)
{
    // ...
}
like image 419
sekmet64 Avatar asked Feb 25 '11 10:02

sekmet64


1 Answers

Short answer: it depends. If the compiler can deduce that running someObject->someFunction() every time and caching the result once both produce the same effects, it is allowed (but not guaranteed) to do so. Whether this static analysis is possible depends on your program: specifically, what the static type of someObject is and what its dynamic type is expected to be, as well as what someFunction() actually does, whether it's virtual, and so on.

In general, if it only needs to be done once, write your code in such a way that it can only be done once, bypassing the need to worry about what the compiler might be doing:

int start = (a - 1) * b;
int expra = a * b;
int exprb = someObject->someFunction();
for (int i = start; i < expra && i < exprb; i++)
    // ...

Or, if you're into being concise:

for (int i = (a - 1) * b, expra = a * b, exprb = someObject->someFunction();
     i < expra && i < exprb; i++)
    // ...
like image 197
Jon Purdy Avatar answered Oct 20 '22 19:10

Jon Purdy