简体   繁体   中英

Can modern compilers optimize constant expressions where the expression is derived from a function?

It is my understanding that modern c++ compilers take shortcuts on things like:

if(true)
{do stuff}

But how about something like:

bool foo(){return true}
...
if(foo())
{do stuff}

Or:

class Functor
{

 public:
        bool operator() () { return true;}

}

...

Functor f;

if(f()){do stuff}

It depends if the compiler can see foo() in the same compilation unit.

With optimization enabled, if foo() is in the same compilation unit as the callers, it will probably inline the call to foo() and then optimization is simplified to the same if (true) check as before.

If you move foo() to a separate compilation unit, the inlining can no longer happen, so most compilers will no longer be able to optimize this code. (Link-time optimization can optimize across compilation units, but it's a lot less common--not all compilers support it and in general it's less effective.)

I've just tried g++ 4.7.2 with -O3 , and in both examples it optimizes out the call. Without -O , it doesn't.

Modern compilers are incredibly clever, and often do "whole program optimization". So as long as you do sensible things, it definitely will optimise away function calls that just return a constant value. The compiler will also inline code that is only called once [even if it is very large], so writing small functions instead of large ones is definitely worth doing. Of course, using the function multiple times, it may not inline it, but then you get better cache hitrate from having the same function called from two places and smallr code overall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM