传递参考的开销是多少? [英] what is the overhead of passing a reference?

查看:77
本文介绍了传递参考的开销是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当相关的getter返回引用时,访问成员变量的代价是多少?

how expensive is it to access a member variable when the getter in question return a reference?

例如,如果您有一个需要经常使用此类访问器的类,那么将所述引用存储在需要使用它并只需将其初始化一次?

for example, if you have a class that needs to use such an accessor fairly often, how much more efficient would it be to store said reference in the class that needs to use it and simply initialise it once?

推荐答案

关于复杂性,返回或传递引用就像传递指针一样。它的开销相当于传递一个指针大小的整数,外加一些指令。简而言之,这几乎在每种情况下都尽可能快。小于或等于指针大小的内置类型(例如int,float)是明显的例外。

Regarding complexity, returning or passing a reference is just like passing a pointer. Its overhead is equivalent to passing an integer the size of a pointer, plus a few instructions. In short, that is as fast as is possible in nearly every case. Builtin types (e.g. int, float) less than or equal to the size of a pointer are the obvious exception.

在最坏的情况下,传递/返回引用可能会增加一些说明或禁用某些优化。这些损失很少超过按值返回/传递对象的成本(例如,即使对于非常基本的对象,调用复制构造函数+析构函数也要高得多)。除非每条指令都算在内,否则按引用传递/返回是一个很好的默认值。

At worst, passing/returning a reference can add a few instructions or disable some optimizations. Those losses rarely exceed the costs of returning/passing objects by value (e.g. calling a copy constructor + destructor is much higher, even for a very basic object). Passing/returning by reference is a good default unless every instruction counts, and you have measured that difference.

因此,使用引用的开销非常低。

Therefore, using references has incredibly low overhead.

在不知道类型及其构造函数/析构函数的复杂性的情况下,无法真正量化出有多少会更快,但是如果它不是内置类型,那么在大多数情况下,保存局部变量并通过引用返回将是最快的-这全都取决于对象及其副本的复杂性,但是只有极少的琐碎对象才能接近引用的速度。

One can't really quantify how much faster it would be without knowing the complexity of your types and their constructor/destructor, but if it is not a builtin type, then holding a local and returning it by reference will be fastest in most cases - it all depends on the complexity of the object and its copy, but only incredibly trivial objects could come close the speed of the reference.

这篇关于传递参考的开销是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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