Why is there overhead when calling functions?

Kamuela Franco picture Kamuela Franco · Aug 3, 2015 · Viewed 13.7k times · Source

Often, people speak of the calling of functions producing a certain amount of overhead, or an inescapable set of additional concerns and circumstances, in a program. Can this be better explained and compared to a similar program without the function call?

Answer

Jens picture Jens · Aug 3, 2015

Also see here and here for a discussion on when inlining would make sense.

  • Inlining

    In general, you can only suggest to the compiler to inline a function, but the compiler might decide otherwise. Visual Studio offers its own forceinline keyword though. Some functions can not be inlined, e.g. when they are recursive or when the target function can not be determined at compile time (calls through function tables, virtual function calls in C++).

    I suggest you trust the compiler whether or not a function should be inlined. If you truly want to inline your code, consider using a macro instead.

  • Overhead

    Memory overhead is at a minimum when you use functions because you do not duplicate code; inlined code is duplicated into the call site. Performance overhead these days is negligible because modern architectures are really good predicting and calling with about 1-2 cycle overhead only.