Here is a fragment of code:
bool EqualsA(const Foo& a, const Foo& b)
{
return a == b;
}
bool EqualsB(const Foo& a, const Foo& b)
{
const bool result = a == b;
return result;
}
int MethodA()
{
return GetValue() * GetOtherValue();
}
int MethodB()
{
const int result = GetValue() * GetOtherValue();
return result;
}
I wanted to know if there is any difference in returning values in these two different ways (instant return or store result in a variable). I think that storing is better for debugging but is there any performance loss (I don't think there is) or any other pros and cons for using one of those.
Under the reasonable assumption that the value returned by the selected overload of
operator ==
for objects of typeFoo
is of typebool
, a decent compiler will optimize your temporary store away when heavy optimization options are used, so as for performance, it does not matter.My advice is to choose the form that makes your code more readable or more convenient to maintain or debug for you.
The compiler is free to optimize away the local variable so the performance is going to be the same.
In a lot of code analysis tools this is marked as a code smell and I would tend to agree. Debuggers can be made to see the return value on the stack so the local variable doesn't buy anything.
There will almost certainly be no difference. The compiler is allowed to do whatever it likes to your code as long as the program behaves as-if it were as you wrote it. So any nice compiler will get rid of the pointless initializations.
However, it's possible for there to be a situation it can't make this initialization disappear. If, for example, an
operator*
overload used forGetValue() * GetOtherValue()
returns a class type result byconst
reference, the constructor of that class type might have some side effects. If it does, the compiler can't get rid of the initialization because it changes the observable behaviour of the program.But why would that not also be the case if the
operator*
returned by value? Then this would be a candidate for copy elision, and the compiler could get rid of the construction regardless of whether it had side effects or not.