user11665591
user11665591

Reputation:

Does calling methods inside methods cause overhead?

Say I have a class with some method f():

class Example
{
  Example();
  ~Example();
  void f();
}

Let's say f() is only a few lines. Let's also say some other method in Example calls f() in itself. Would calling f() in such case cause overhead, as opposed to simply duplicating its code into wherever it's needed?

Upvotes: 0

Views: 75

Answers (3)

JohnkaS
JohnkaS

Reputation: 631

Theoretically it could have overhead without optimizations enabled, however, as a previous answer stated, code inlining is very aggressive nowadays, compilers do it without asking.

The overhead it could possibly have without optimizations is 2 instructions extra, 1: mov this into the register 2: call the function.

However, optimizations will take care of this.

https://godbolt.org/z/wzhSzG

Upvotes: 0

Oblivion
Oblivion

Reputation: 7374

“Premature optimization is the root of all evil” 

Code duplication is a bad practice and some nanoseconds you gain- I doubt, doesn't worth it. You can ask compiler to inline your code or do the ugly macro instead of function and code duplication.

And the answer for overhead is yes and no depends on what and how you are doing.

Upvotes: 0

Michael Chourdakis
Michael Chourdakis

Reputation: 11158

It's called function inlining, and let the compiler do it automatically. Nowadays compilers are very aggressive with it.

Upvotes: 2

Related Questions