C#在速度方面将结构引用和类引用传递给方法之间有区别吗? [英] C# is there a difference between passing a struct reference and a class reference to a method in terms of speed?

查看:104
本文介绍了C#在速度方面将结构引用和类引用传递给方法之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,结构是通过副本传递的,而类是通过引用传递的。但是为什么为什么使用ref关键字通过引用传递结构仍然比传递对类的引用慢呢?

As seen here, structs are passed by copy and classes by reference. But why is passing a struct by reference using the ref keyword still slower than passing a reference to a class ?

我通过替换<$ c来获得不同的速度具有的$ c> struct 个关键字。所有变量都已经通过 ref 关键字传递。

通过更改关键字,我的测试速度提高了20%。自从我已经通过引用传递以来,速度应该保持不变吗?我不明白什么?

I got different speeds for my program by replacing the struct keywords with class. All of the variables were already passed with the ref keyword.
By changing keywords, I got 20% speed increase in my tests. Shoudn't the speed remain the same since I was already passing by reference ? What am I not understanding ?

推荐答案

通过 ref 传递结构与按值传递类(指向数据的指针)相同,通过 ref (指向数据指针的指针)传递类应该比按值传递类作为额外的取消引用要慢一些

Passing struct by ref is roughly the same as passing class by value (pointer to data), passing class by ref (pointer to pointer to data) should be a bit slower than passing class by value as extra dereference required.

是否从将按值传递结构替换为按引用传递结构是否获得速度改进取决于结构的大小。如果您遵循 Microsoft的指导结构的大小< = 16字节,无论如何该差异可能都是微不足道的,否则,如果结构很大,您可能会看到一些性能提升。

Whether you get speed improvements or not from replacing "pass struct by value" to "pass struct by ref" depends on size of struct. If you follow Microsoft's guidance "size of struct <= 16 bytes" the difference will likely be insignificant anyway, otherwise if struct is huge you likely see some performance gains.

潜在的收益/损失还取决于32位与64位(x86 / x64)CPU体系结构的选择-如果性能在您的情况下如此重要,请在目标计算机上仔细进行测量。

The potential gains/losses also depend on 32bit vs. 64bit (x86/x64) CPU architecture choice - measure carefully on target machines if performance is so important in your case.

注意:通过ref传递struct通常将类型的选择限制为数组和字段-确保您愿意接受这种限制。

Note: passing struct by ref generally limit choices of type to arrays and fields - make sure you are willing to live with such restriction.

这篇关于C#在速度方面将结构引用和类引用传递给方法之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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