Member functions same as passing reference to global function?
Can I be sure that:
class foo {
public:
int x;
开发者_JS百科 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 both will set "x" to "k", but can I be sure that they both perform at same speed / generate same asm? Can the compiler optimize methods greater?
Generate the assembler and compare (-S
flag for GCC).
In a few cases, it can make a difference in the generated assembly code, but (at least usually) not much.
For example, Microsoft's compiler will (normally) use what they call thiscall
calling convention for member functions, in which case, the this
pointer is passed in register ECX. Global functions default to the cdecl
calling convention, in which the parameters are all passed on the stack. It's also possible, however, to tell the compiler to use the fastcall
calling convention, in which the first two parameters are passed in ECX and EDX respectively (so as long as you pass the imitation-this
as the first parameter, it ends up the same as thiscall
).
Years ago (e.g., 286, 386 time-frame), passing parameters in registers instead of on the stack saved quite a bit of time. Now that most CPUs have at least a few megabytes of on-board cache, most of that difference has disappeared.
I know both will set "x" to "k", but can I be sure that they both perform at same speed / generate same asm?
Practically, you can be sure it doesn't matter. If you think it matters, then profile and compare the differences, or look at asm output from your compiler.
Can the compiler optimize methods greater?
Generally it cannot. Especially for short, inline, non-virtual functions as in your example (you need to mark foobar as inline to be exactly equivalent to the first piece of code), the function call in either case is likely to simply disappear.
The first example has foo::bar in the virtual function table for class foo. The second does not. That makes it a tiny bit more space efficient. Since foobar is not virtual, the compiler can probably do more in the way of optimization.
精彩评论