Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is (*i).member less efficient than i->member

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)?

like image 540
Kalamar Obliwy Avatar asked May 03 '13 09:05

Kalamar Obliwy


People also ask

Is I++ or++ I more efficient?

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."

Which is better i i 1 or i ++ from compilers perspective?

I++ is faster!

Are structs efficient?

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.


2 Answers

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.

like image 93
Luchian Grigore Avatar answered Sep 18 '22 15:09

Luchian Grigore


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)

like image 44
Gui13 Avatar answered Sep 21 '22 15:09

Gui13