Which is more efficient: Return a value vs. Pass by reference?

thegreatjedi picture thegreatjedi · Nov 30, 2015 · Viewed 26k times · Source

I am currently studying how to write efficient C++ code, and on the matter of function calls, a question comes to mind. Comparing this pseudocode function:

not-void function-name () {
    do-something
    return value;
}
int main () {
    ...
    arg = function-name();
    ...
}

with this otherwise-identical pseudocode function:

void function-name (not-void& arg) {
    do-something
    arg = value;
}
int main () {
    ...
    function-name(arg);
    ...
}

Which version is more efficient, and in what respect (time, memory etc.)? If it depends, then when would the first be more efficient and when would the more efficient be the second?

Edit: For context, this question is limited to hardware platform-independent differences, and for the most part software too. Are there any machine-independent performance difference?

Edit: I don't see how this is a duplicate. The other question is comparing passing by reference (prev. code) to passing by value (below):

not-void function-name (not-void arg)

Which is not the same thing as my question. My focus is not on which is the better way to pass in an argument to a function. My focus is on which is the better way to pass out a result to a variable from the outside scope.

Answer

arodriguezdonaire picture arodriguezdonaire · Nov 30, 2015

First of all, take in account that returning an object will always be more readable (and very similar in performance) than having it passed by reference, so could be more interesting for your project to return the object and increase readability without having important performance differences. If you want to know how to have the lowest cost, the thing is what do you need to return:

  1. If you need to return a simple or basic object, the performance would be similar in both cases.

  2. If the object is so large and complex, returning it would need a copy, and it could be slower than having it as a referenced parameter, but it would spend less memory I think.

You have to think anyway that compilers do a lot of optimizations which make both performances very similar. See Copy Elision.