3

I understand inlining as the following:

A separate function which is marked as "inline" (assuming the compiler really does inline) will be "merged" into the function it is called.

i.e. (pseudo code)

void main ()
{
  printf(b(2,3))  // will be printf(2*3*3);
}
inline function b(int x, int y)
{
  return x*y*y;
}

However, I had a discussion regarding inlining and why am I advised to not inline functions that are called exactly once in my code(Because they are initialization functions)?

For example:

void main(){
    initFunctionA();
    SomeType destinationA;
    SomeType destinationB;
    InitDescriptionType description;
    //initialize DescriptionType
    initFunctionB(&description, destinationA&);
    initFunctionC(&description, destinationB&);
}

inline void initFunctionA()
{
    //do stuff
}
inline void initFunctionB(InitDescriptionType* desc, SomeType** destination)
{
    // Take Description and put something into destination
}
inline void initFunction(InitDescriptionType* desc, SomeType** destination)
{
    // Take Description and put something into destination
}

Wouldn't that mean that my output code is marginally smaller (since no jumps to functions etc?)

€dit: The linked question doesn't answer my particular question. In my Case, the Initialization is a single function. My thought was "Hey, why don't I separate my Initizalization into multiple smaller functions for readability and make them inline?"

7

In C and C++, the inline keyword has effects that make inline possible, but also many other effects – such as suppressing the one-definition rule (ODR). This can obscure bugs.

Therefore, the inline keyword should only be used for functions and other objects that must be defined in a header anyway. In particular, any function definitions within a C++ class definition are already implicitly inline.

But if you merely want to make inlining optimizations possible for the compiler, give those functions internal linkage instead. This is possible through the static keyword, or since C++11 through anonymous namespaces.

Note that if a function call is only performed once per program execution, then optimizing that function call is not worth it. You will literally not be able to notice any difference in performance. Rather than optimizing initialization code, find the real bottlenecks:

  1. Determine your actual performance requirements.
  2. Profile your code to find hot spots and expensive operations.
  3. Find ways to avoid those expensive operations. In hot spots, micro-optimizations can sometimes pay off.
  4. Repeat steps 2 and 3 until your performance requirements are met.

See also:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.