NET]为什么结构少于16个字节会更好 [英] NET] Why is struct better with being less than 16 bytes

查看:72
本文介绍了NET]为什么结构少于16个字节会更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究.NET结构-有些书建议如果实例大小小于16个字节,则创建结构。



为什么?

解决方案

这是因为16字节是阈值,编译器开始将结构复制为内存块,而不是使用一个或两个简单的移动指令。 p>

当结构很小时,编译器会优化结构的复制。可以将例如八个字节的结构复制为单个64位值。可以将一个16字节的结构复制为一个或两个奇异值(取决于处理器体系结构)。当结构大于16个字节时,编译器将不再尝试优化移动,而后退方法是调用复制内存块的方法。



(注意:16字节的阈值可能会因编译器的版本而异,似乎在更新的版本中它实际上试图进行优化,但是与复制相比,优化后的代码仍然会有很多移动指令



编辑:

这是我对自己的测试的结果64位系统复制将执行十亿次操作:

 结构4:272毫秒。 
struct 8:235毫秒。
struct 16:317毫秒
struct 32:625毫秒
struct 64:1280毫秒
struct 128:4659毫秒
结构256:8020毫秒

如您所见,时间在16字节以下不是线性的,尽管16字节是四倍作为4个字节,它不会花费四倍的时间。在16个字节以上,时间是线性的,因此将大小加倍是时间。那就是开始使用多个动作的地方。在64字节以上有一个跳转,当大小增加一倍时,时间突然变成三倍。这就是开始使用后备功能的地方。


I'm studying .NET structs - some books advise creating structs if they have an instance size less than 16 bytes.

Why is that?

解决方案

It's because 16 bytes is the threshold where the compiler starts copying structs as block of memory instead of using one or two simple move instructions.

The compiler optimises the copying of structures when they are small. A struct that is for example eight bytes can be copied as a single 64 bit value. A struct that is 16 bytes can be copies as one or two singular values (depending on the processor architecture). When the structure is larger than 16 bytes, the compiler doesn't try to optimise the move any more, and the fallback is to call a method that copies a block of memory.

(Note: the threshold of 16 bytes may differ depending on the version of compiler, it seems as it actually tries to optimise beyond that point in newer versions, but the optimised code will still be a lot of move instructions, compared to copying a reference to an object which still is a single move operation.)

Edit:
Here is the result of a test that I did on my 64 bit system copying structs half a billion times:

struct 4    : 272 ms.
struct 8    : 235 ms.
struct 16   : 317 ms.
struct 32   : 625 ms.
struct 64   : 1280 ms.
struct 128  : 4659 ms.
struct 256  : 8020 ms.

As you see, below 16 bytes the time is not linear, although 16 bytes is four times as much as 4 bytes, it doesn't take four times longer. Above 16 bytes the time is linear, so doubling the size double the time. That's where it would start using multiple moves. Above 64 bytes there is a jump, where the time suddenly quadruples when the size doubles. That's where the fallback would start to be used.

这篇关于NET]为什么结构少于16个字节会更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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