Reputation: 3044
Code A:
string a = "Hello World";
for (int i=0; i<1000000; ++i)
const string b = a;
Code B:
string a = "Hello World";
for (int i=0; i<1000000; ++i)
const string &b = a;
If I run the 2 codes separately and measure CPU time, the Code B was about 2.5 times faster than the Code A.
Except for the primitive types such as char
, int
, float
... I learned it is faster to get a reference to the original rather than copying it.
Although the difference is almost neglectable in most cases, can it be considered as a good practice to always make const string
type(and other non-primitive types) be referenced?
Upvotes: 4
Views: 269
Reputation: 308196
Yes, it is generally better to use a const reference for any object that is expensive to copy. But you must take care that the original object doesn't change when you don't expect it; in particular you need to make sure that the original object isn't destroyed, because that leads to undefined behavior. That isn't a problem in your toy example, but in the real world it's a big concern.
The best place to use a const reference is in function parameters. You know that the object passed into the function can't change or be destroyed while still inside the function.
Upvotes: 3
Reputation: 10425
There's a couple of things to take into account.
If you wish to merely observe the object:
If the type of the object allocates dynamic memory on copy, then always pass by const reference.
Otherwise if the sizeof
of the type is larger than sizeof(void*)
then pass by const reference.
Otherwise pass by value.
If you wish to copy the object, then just pass by value.
Of course in a strange use case you may do something else, but this is the general guideline that I see is commonly followed.
There's also move semantics to take into account, but that's a different question.
Upvotes: 2