void do_something() {....}
struct dummy
{
//even I dont call this, compiler will call it fall me, they need it
void call_do_something() { this->do_something_member(); }
void do_something() {....}
};
According what I know, every class or struct in C++ will implicity call
this pointer when you want to access the data member or the member function
of the class, would this bring performance penalty to C++?
What I mean is
int main()
{
do_something(); //don't need this pointer
dummy().call_do_something(); //assume the inline is prefect
return 0;
}
call_do_something need a this pointer to call the member function, but
the C like do_something don’t need this pointer, would this pointer bring
some performance penalty when compare to the C like function?
I have no meaning to do any micro optimization since it would cause me so much
time but always don’t bring me good result, I always follow the rule of “measure, don’t think”.
I want to know this pointer would bring performance penalty or not because of curiosity.
Depends on the situation, but usually, if you’ve got optimizations turned on, it shouldn’t be any more expensive than the C version. The only time you really “pay” for
thisand other features is when you’re using inheritance and virtual functions. Other than that, the compiler is smart enough to not waste time onthisin a function you’re not using it. Consider the following:Compiled with GCC optimization level
O3, I get the following disassembly (cutting the extra junk and just showingmain()):Notice it completely optimized away both the
DummyandglobalDoStuff()and just replaced it with the body ofglobalDoStuff().globalDoStuff()isn’t ever even called, and noDummyis ever constructed. Instead, the compiler/optimizer replaces that code with two system calls to print out"Hello world!\n"directly. The lesson is that the compiler and optimizer is pretty dang smart, and in general you won’t pay for what you don’t need.On the other hand, imagine you have a member function that manipulates a member variable of
Dummy. You might think this has a penalty compared to a C function, right? Probably not, because the C function needs a pointer to an object to modify, which, when you think about it, is exactly what thethispointer is to begin with.So in general you won’t pay extra for
thisin C++ compared to C. Virtual functions may have a (small) penalty as it has to look up the proper function to call, but that’s not the case we’re considering here.If you don’t turn on optimizations in your compiler, then yeah, sure, there might be a penalty involved, but… why would you compare non-optimized code?