哪个更有效:返回值与通过引用传递?

我目前正在研究如何编写高效的C++代码,关于函数调用的问题,想到了一个问题.比较这个伪代码函数:

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.

推荐答案

首先,考虑到返回一个对象总是比通过引用传递更具可读性(并且在性能上非常相似),所以可以您的项目更有趣的是返回对象并提高可读性,而不会产生重要的性能差异.如果你想知道如何以最低的成本,那么你需要返回什么:

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. 如果您需要返回一个简单或基本的对象,两种情况下的性能会相似.

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

如果对象如此大和复杂,返回它需要一个副本,它可能比将其作为引用参数慢,但我认为它会花费更少的内存.

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.

相关文章