Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do compilers optimize out parameters that aren't used?

Suppose I have a very simple inline function:

void Trace(int i)
{
#ifdef _DEBUG
    std::cout << i << std::endl;
#endif
}

Now I call this function with the parameter generated by another function that takes a long time:

Trace(SlowFunc());

Will a reasonable compiler optimize out the call to SlowFunc() in release mode? Specifically will MSVC do it?

like image 555
Mark Ransom Avatar asked Oct 02 '18 16:10

Mark Ransom


1 Answers

The optimization would only be allowed if SlowFunc() is proven to have no side effects - but in practice, long-running functions are usually ridden with side-effects (unless it is some sort of heavy computational math, but then the optimizer might give up on it). If SlowFunc() is proven to have no side effects, this call can be optimized out.

But I would not rely on it. Instead, use a logging solution which only calculates the argument when DEBUG is enabled. There are a couple of options, let me know if you'd like some pointers.

like image 57
SergeyA Avatar answered Sep 23 '22 05:09

SergeyA