Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are compilers smart enough to detect a no-op function?

Tags:

c++

If I write a function like this:

void doMaybeNothing()
{ 
#ifndef IM_LAZY
   doSomething();
#endif
}

Are modern compilers smart enough to detect a no-op function and optimize so that there are no cycles wasted? Or is there always a small performance impact?

like image 834
Thijs Koerselman Avatar asked Dec 12 '22 21:12

Thijs Koerselman


1 Answers

Assuming the body of the function is available at compile-time or link-time (i.e., it's not in a dynamically linked library), most modern compilers should get rid of calls to functions that do nothing (if optimizations are enabled, of course).

Effectively, this is just a form of inline expansion, which allows the body of a function to be expanded anywhere it is called, so long as the results are the same. If the function does nothing, then it will simply expand to nothing wherever it is inlined.

like image 173
James McNellis Avatar answered Dec 27 '22 21:12

James McNellis