根据经验,何时按值传递比按const引用传递更快? [英] Rule of thumb for when passing by value is faster than passing by const reference?

查看:82
本文介绍了根据经验,何时按值传递比按const引用传递更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数,其参数类型为 T
它不会突变,因此我可以选择通过const引用 const T& 或值 T

Suppose I have a function that takes an argument of type T. It does not mutate it, so I have the choice of passing it by const reference const T& or by value T:

void foo(T t){ ... }
void foo(const T& t){ ... }

T 应该在通过const引用传递之前变得比通过值传递便宜吗?例如,假设我知道 sizeof(T)== 24 。我应该使用const引用还是值?

Is there a rule of thumb of how big T should become before passing by const reference becomes cheaper than passing by value? E.g., suppose I know that sizeof(T) == 24. Should I use const reference or value?

我认为 T 的副本构造函数很简单。否则,问题的答案当然取决于复制构造函数的复杂性。

I assume that the copy constructor of T is trivial. Otherwise, the answer to the question depends on the complexity of the copy constructor, of course.

我已经在寻找类似的问题,偶然发现了这个问题:

I have already looked for similar questions and stumbled upon this one:

通过值传递模板还是const引用还是...?

但是,可接受的答案(
https://stackoverflow.com/a/4876937/1408611 )未声明任何详细信息,仅声明:

However, the accepted answer ( https://stackoverflow.com/a/4876937/1408611 ) does not state any details,it merely states:


如果您希望T始终是数字类型或很便宜的
复制类型,则可以按值接受参数。

If you expect T always to be a numeric type or a type that is very cheap to copy, then you can take the argument by value.

所以它不能解决我的问题,而是改写:类型必须小到要复制很便宜?

So it does not solve my question but rather rephrases it: How small must a type be to be "very cheap to copy"?

推荐答案

如果您有理由怀疑这样做会带来有价值的性能提升, d,用经验法则和措施将其删除。您引用的建议的目的在于,您不会无缘无故地复制大量数据,但也不要通过将所有内容都当作参考来危及优化。如果复制显然很便宜和复制显然很昂贵之间处于边缘,那么您可以负担得起。

If you have reason to suspect there is a worthwhile performance gain to be had, cut it out with the rules of thumb and measure. The purpose of the advise you quote is that you don't copy great amounts of data for no reason, but don't jeopardize optimizations by making everything a reference either. If something is on the edge between "clearly cheap to copy" and "clearly expensive to copy", then you can afford either option. If you must have the decision taken away from you, flip a coin.

如果没有时髦的复制构造函数且其 sizeof 很小。没有最优的硬数字,即使在每个平台上也没有,因为它在很大程度上取决于调用代码和函数本身。随你的直觉去吧。一,二,三个字很小。十,谁知道。 4x4矩阵不小。

A type is cheap to copy if it has no funky copy constructor and its sizeof is small. There is no hard number for "small" that's optimal, not even on a per-platform basis since it depends very much on the calling code and the function itself. Just go by your gut feeling. One, two, three words are small. Ten, who knows. A 4x4 matrix is not small.

这篇关于根据经验,何时按值传递比按const引用传递更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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