Consider the following :
int increment1 (const int & x)
{ retur开发者_如何学JAVAn x+1; }
int increment2 (const int x)
{ return x+1; }
I understand passing references to class objects an such, but I'm wondering if it's worth to pass reference to simple types ? Which is more optimal ? Passing by reference or passing by value (in case of a simle type?)
Unless you need the "call by reference" semantics, i.e. you want to access the actual variable in the callee, you shouldn't use call by reference for simple types.
For a similar, more general discussion see: "const T &arg" vs. "T arg"
Do you also understand premature optimization? :)
Do what is clearest. If the function is going to return the value, it does not need a reference. A (human!) reader of the code might then wonder why a reference is being used, for no good reason.
UPDATE: If you want the function to be called increment()
, that (to me) implies it should change the passed-in value, and not return it. It sounds like a modify in place kind of operation. Then it might make sense to use a reference (or pointer), and remove the return value:
void increment(int &value)
{
++value;
}
If you're investigating what is fastest, I still think you're optimizing prematurely.
It maybe doesn't "worth", but it is sometimes different. Consider these functions:
int const* addr_ref (int const& i) { return &i; }
int const* addr_byvalue(int const i) { return &i; }
They obviously return different values. So sometimes it's useful.
In the meantime you should stick to your coding convention. Most likely compiler's optimization within the function will discard unnecessary dereferences, and in the caller code it was using reference as well, so the performance is hardly an issue here.
If the functions are templated you have a harder time making the choice. Should T be accepted by value or by const reference, when you don't know how big or expensive to copy T is?
In this case I would prefer passing by const reference. If the size of T is less than or equal to the size of a reference, it's possible for the compiler to perform an optimisation: it simply passes the parameter by value anyway, because a const reference parameter promises not to modify the parameter, so the side effects are the same. However, the compiler may also choose not to perform this optimisation, especially if it has trouble working out if there are any const_casts involved and such.
But for that reason, I would side with passing by const reference - it's possible, but not certain, that a clever compiler can choose the correct pass method for you, depending on the size of the type and the architecture.
精彩评论