Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much overhead is there in calling a function in C++?

A lot of literature talks about using inline functions to "avoid the overhead of a function call". However I haven't seen quantifiable data. What is the actual overhead of a function call i.e. what sort of performance increase do we achieve by inlining functions?

like image 681
Obediah Stane Avatar asked Sep 28 '08 02:09

Obediah Stane


People also ask

What is the overhead of a function call?

This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run.

Is calling a function expensive?

Speaking from personal experience, I write code in a proprietary language that is fairly modern in terms of capability, but function calls are ridiculously expensive, to the point where even typical for loops have to be optimized for speed: for(Integer index = 0, size = someList.

Is calling a function slow?

Yes method calls slow down the code execution a tiny little bit, if they a not inlined by the c#-compiler or the jit-compiler. However, unless your code runs in a loop and is executed a million times or so, you should really focus on producing clean, understandable and maintainable code.

What happens when we call function in C?

Series of operations when we call a function:Stack Frame is pushed into stack. Sub-routine instructions are executed. Stack Frame is popped from the stack. Now Program Counter is holding the return address.


1 Answers

On most architectures, the cost consists of saving all (or some, or none) of the registers to the stack, pushing the function arguments to the stack (or putting them in registers), incrementing the stack pointer and jumping to the beginning of the new code. Then when the function is done, you have to restore the registers from the stack. This webpage has a description of what's involved in the various calling conventions.

Most C++ compilers are smart enough now to inline functions for you. The inline keyword is just a hint to the compiler. Some will even do inlining across translation units where they decide it's helpful.

like image 154
Eclipse Avatar answered Oct 10 '22 23:10

Eclipse