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

淺唱寂寞╮ 提交于 2019-12-23 13:58:36

问题


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}

回答1:


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.)




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/13995659/can-modern-compilers-optimize-constant-expressions-where-the-expression-is-deriv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!