Performance – Impact of Function Calls on Performance

object-orientedperformanceprogramming-languages

Extracting functionality into methods or functions is a must for code modularity, readability and interoperability, especially in OOP.

But this means more functions calls will be made.

How does splitting our code into methods or functions actually impact performance in modern* languages?

*The most popular ones: C, Java, C++, C#, Python, JavaScript, Ruby…

Best Answer

Maybe. The compiler might decide "hey, this function is only called a few times, and I'm supposed to optimize for speed, so I'll just inline this function". Essentially, the compiler will replace the function call with the body of the function. For example, the source code would look like this.

void DoSomething()
{
   a = a + 1;
   DoSomethingElse(a);
}

void DoSomethingElse(int a)
{
   b = a + 3;
}

The compiler decides to inline DoSomethingElse, and the code becomes

void DoSomething()
{
   a = a + 1;
   b = a + 3;
}

When functions are not inlined, yes there is a performance hit to make a function call. However, it's such a minuscule hit that only extremely high performance code is going to worry about function calls. And on those kinds of projects, the code is typically written in assembly.

Function calls (depending on the platform) typically involve a few 10s of instructions, and that's including saving / restoring the stack. Some function calls consist a jump and return instruction.

But there's other things that might impact function call performance. The function being called may not be loaded into the processor's cache, causing a cache miss and forcing the memory controller to grab the function from main RAM. This can cause a big hit for performance.

In a nutshell: function calls may or may not impact performance. The only way to tell is to profile your code. Don't try to guess where the slow code spots are, because the compiler and hardware have some incredible tricks up their sleeves. Profile the code to get the location of the slow spots.