通过引用传递原始类型而不是通过值返回有什么效率优势? [英] Any efficiency benefit to passing primitive types by reference instead of returning by value?

查看:50
本文介绍了通过引用传递原始类型而不是通过值返回有什么效率优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,通过引用传递原始类型而不是通过值返回是否有效率优势?

In C++, is there an efficiency benefit in passing primitive types by reference instead of returning by value?

推荐答案

[...] 通过引用传递原始类型而不是通过值返回是否有效率优势?

[...] is there an efficiency benefit to passing primitive types by reference instead of returning by value?

不太可能.首先,除非您有来自分析器的数据,否则您在设计程序时不应该担心性能问题.选择最简单的设计,以及最能传达您的意图的设计.

Unlikely. First of all, unless you have data from your profiler that give you a reason for doing otherwise, you should not worry about performance issues when designing your program. Choose the simplest design, and the design that best communicates your intent.

此外,原始类型的复制成本通常较低,因此这不太可能成为您的应用程序的瓶颈.并且因为它是最简单的选项,也是让函数界面最清晰的选项,你应该传值.

Moreover, primitive types are usually cheap to copy, so this is unlikely to be the bottleneck in your application. And since it is the simplest option and the one that makes the interface of the function clearest, you should pass by value.

单看签名,很明显是一个函数如:

Just looking at the signature, it is clear that a function such as:

void foo(int);

不会存储对参数的引用(因此,不会遇到诸如悬空引用或指针之类的问题),不会以调用者可见的方式更改参数,等等.

Will not store a reference to the argument (and consequently, won't run into issues such as dangling references or pointers), will not alter the argument in a way that is visible to the caller, and so on and so on.

以上都不能从如下函数签名中推导出来:

None of the above can be deduced from a function signature like:

void f(int&); // May modify the argument! Will it? Who knows...

甚至:

void f(int const&); // May store a reference! Will it? Who knows...

此外,通过允许编译器执行潜在的别名会阻止的优化,按值传递甚至可以提高性能.

Besides, passing by value may even improve performance by allowing the compiler to perform optimizations that potential aliasing would prevent.

当然,所有这一切都是在假设您实际上不需要修改函数内部的参数的方式,即在函数返回后调用者可以看到该参数的副作用 - 或者存储一个参考那个论点.

Of course, all of this is under the assumption that you do not actually need to modify the argument inside the function in a way that side-effects on that argument will be visible to the caller after the function returns - or store a reference to that argument.

如果是这种情况,那么您当然应该通过引用传递并使用适当的const 限定.

If that is the case, then you should of course pass by reference and use the appropriate const qualification.

有关更广泛的讨论,另请参阅此问答StackOverflow.

For a broader discussion, also see this Q&A on StackOverflow.

这篇关于通过引用传递原始类型而不是通过值返回有什么效率优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆