Having
struct Person {
string name;
};
Person* p = ...
Assume that no operators are overloaded.
Which is more efficient (if any) ?
(*p).name
vs. p->name
Somewhere in the back of my head I hear some bells ringing, that the *
dereference operator may create a temporary copy of an object; is this true?
The background of this question are cases like this:
Person& Person::someFunction(){
...
return *this;
}
and I began to wonder, if changing the result to Person*
and the last line to simply return this
would make any difference (in performance)?
According to the Google C++ Style Guide, "when the return value is ignored, the 'pre' form ( ++i ) is never less efficient than the 'post' form ( i++ ), and is often more efficient."
I++ is faster!
Using struct has traditionally been more efficient, as searching for the correct method can be expensive. The performance of classes was significantly worse before Mathworks implemented the Execution Engine several releases ago.
There's no difference. Even the standard says the two are equivalent, and if there's any compiler out there that doesn't generate the same binary for both versions, it's a bad one.
When you return a reference, that's exactly the same as passing back a pointer, pointer semantics excluded.
You pass back a sizeof(void*)
element, not a sizeof(yourClass)
.
So when you do that:
Person& Person::someFunction(){
...
return *this;
}
You return a reference, and that reference has the same intrinsic size than a pointer, so there's no runtime difference.
Same goes for your use of (*i).name
, but in that case you create an l-value, which has then the same semantics as a reference (see also here)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With