通过引用传递原始类型是否适得其反? [英] Is it counter-productive to pass primitive types by reference?

查看:153
本文介绍了通过引用传递原始类型是否适得其反?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:



不能通过引用传递简单类型的原因?

我做了一些测试,其中我有两个方案,每个方案有两个相同的功能 - 一个通过参考传递参数,另一个值。带字符串的场景表现出巨大的性能提升(因为字符串的副本被调用,调用构造函数),而使用long的测试在通过引用传递值时没有显示任何性能提升。实际上,有时性能更差。

I did some testing where I had two scenarios, each with two identical functions- one passing the parameter by reference and the other by value. The scenario with strings showed a massive performance increase (because a copy of string is made, calling a constructor) whereas the test with long didn't show any performance increase when passing the value by reference. In fact, sometimes the performance was worse.

这是原始类型吗?是否有没有点通过引用传递?

Is this expected with primitive types? Is there no point passing them by reference?

我期望一个原始类型的副本,当不使用通过引用,因此期望一个小的性能提升。 / p>

I was expecting a copy of a primitive type is made when not using by reference and therefore expected a small performance-boost.

推荐答案

通过值传递原始类型,可以获得最佳性能。这是因为:

You get the best performance from passing primitive types by value. This is because:


  • 原语是blitable,所以复制的成本取决于大小

  • 原始元素很小,在大多数环境中只有 double long long 大于参考
  • $ b
  • pass-by-value避免别名混淆,允许优化器真正做到它

  • primitives are blitable, so the cost of the copy depends on the size
  • primitives are small, only double and long long are bigger than a reference in most environments
  • pass-by-value avoids aliasing, allowing the optimizer to really do its thing

这最后一点经常被忽略,但可以产生相当大的差异。

This last point is often overlooked but can make a considerable difference.

这篇关于通过引用传递原始类型是否适得其反?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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