Are member functions the same as passing a reference to a global function?

Can I be sure that:

class foo {
  public:
  int x;
  void bar(int k) {
    x = k;
  }
};
foo o;
o.bar(5);

Will be the same as:

class foo {
  public:
  int x;
};

void foobar(foo& f, int k) {
  f.x = k;
}

foo o;
foobar(o, 5);

I know that both will set "x" to "k", but can I be sure that they both perform at the same speed / generate the same asm? Can the compiler optimize methods more?

+3
source share
4 answers

I know that both will set "x" to "k", but can I be sure that they both perform at the same speed / generate the same asm?

In practice, you can be sure that it does not matter. If you think this matters, then profile and compare the differences, or look at the asm output from your compiler.

?

, . , , , ( foobar inline, ), , , .

+1

( -S GCC).

+3

, ( , ) .

, Microsoft () , thiscall -, this ECX. cdecl, . fastcall, ECX EDX ( , - this , , thiscall).

A few years ago (for example, 286, 386 time frames), passing parameters in registers, and not on the stack, saved quite a lot of time. Now that most processors have at least a few megabytes of internal cache, most of this difference has disappeared.

+2
source

The first example has foo :: bar in the virtual function table for the class foo. The second is not. This makes it a little more economical. Since foobar is not virtual, the compiler can probably do more in the optimization path.

-2
source

Source: https://habr.com/ru/post/1791895/


All Articles