Home > Software design >  inline function in an array of functions, good idea for performance?
inline function in an array of functions, good idea for performance?

Time:08-13

The question is in the title but it's not necessarily clear so here's a code example of what I wanted to do:

#include <iostream>

typedef void (*functions)(void);

inline void func_A()
{
    std::cout << "I am A !" << std::endl;
}

inline void func_B()
{
    std::cout << "I am B !" << std::endl;
}

int main()
{
    functions funcs[2] = {func_A, func_B};

    for (int i = 0; i < 2; i  )
        funcs[i]();

    return 0;
}

Is this a good idea compared to the interest of an inline function? Does the compiler handle this well?

Thanks in advance !

CodePudding user response:

You can easily look at the output of the compilers to see how they handle your code. Here my results for current compilers with O2 optimization flags, see https://godbolt.org/z/ecjjz88hs.

Current MSVC seems to not optimize the calls at all. It doesn't even unroll the loop and therefore also doesn't determine which functions are actually indirectly called and also consequently can't inline the function calls.

GCC 12.1 does unroll the loop and turns the indirect function calls into direct function calls, but decides not to inline them.

Clang 14.0.0 does unroll the loop and also does inline the two calls to func_A and func_B.


Note that these results can easily change if you change the details of your example, in particular the number of functions called. It is also non-obvious that inlining the function calls is the best decision here. Compared to the cout << statements the function call overhead is negligible.

The inline keyword on the functions has no impact on these behaviors. The compilers considered above behave exactly the same with or without it.


inline may be a hint to the compiler that the function should be considered for inlining. But that is only a very secondary purpose of the keyword. Compilers will consider non-inline functions for inlining as well and mainly use internal heuristics to decide whether inlining is appropriate or not.

The main purpose of the inline keyword is to be able to define a function in a header file. An inline function definition may (in contrast to a non-inline one) appear in multiple translation units. (In fact an inline function must have its definition appear in any translation unit using that function.) This helps inlining by giving the compiler access to the definition of the function directly in the translation unit using it. Without link-time optimization (LTO) compilers can't really inline function calls across translation units.

If a function is meant to be used in only one translation unit anyway, then it should be marked static, not inline, so that it cannot conflict with other functions of the same name that are meant to be local to another translation unit.

  •  Tags:  
  • c
  • Related