Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an empty function called at all in optimised code?

If the TEST macro is not defined, I would like to know whether there is a performance difference in these two pieces of code:

void Func1(int a) {
   // ...
}

#ifdef TEST
Func1(123);
#endif

and:

void Func2(int a) {
#ifdef TEST
    // ...
#endif
}

Func2(123);

With TEST not defined, Func2 would become an empty function that the compiler should not call at all, isn't it?

like image 281
Pietro Avatar asked Jul 01 '11 11:07

Pietro


People also ask

Is Empty function in C++?

The list::empty() is a built-in function in C++ STL is used to check whether a particular list container is empty or not. This function does not modifies the list, it simply checks whether a list is empty or not, i.e. the size of list is zero or not.

How to define empty function in Python?

In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement. We can use pass in empty while statement also.


1 Answers

It pretty much comes down to whether that particular call to Func2 is inlined or not. If it is, then an optimizing compiler ought to be able to make an inlined call to an empty function the same as not calling it at all. If it isn't inlined, then it's called and returns immediately.

As long as the function definition is available in the TU containing the call to Func2, there's no obvious reason it won't be inlined.

This all relies on the fact that 123 is a literal, so evaluating the arguments of your call has no side-effects. The args have to be evaluated even if the function call has no effect, so:

int i = 0;

/* 'i' is incremented, even if the call is optimized out */
Func2(++i);

/* 'i' is not incremented when 'TEST' is undefined */
#ifdef TEST
Func1(++i);
#endif
like image 167
Steve Jessop Avatar answered Oct 25 '22 21:10

Steve Jessop