为什么一个.NET结构小于16字节? [英] Why should a .NET struct be less than 16 bytes?

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

问题描述

我读过的,现在一些地方的最大实例大小的结构应该是16个字节。

I've read in a few places now that the maximum instance size for a struct should be 16 bytes.

但我不能看到这个数字(16)的由来。

But I cannot see where that number (16) comes from.

四处撒网浏览,我发现了一些谁认为这是个概数为出色的表现,但微软说话就像是一个硬上限。 (例如: MSDN

Browsing around the net, I've found some who suggest that it's an approximate number for good performance but Microsoft talk like it is a hard upper limit. (e.g. MSDN )

有没有人有关于为什么是16个字节一个明确的答案?

Does anyone have a definitive answer about why it is 16 bytes?

推荐答案

有经验只是一个表现的规则。

It is just a performance rule of thumb.

的一点是,因为值类型是按值传递,该结构的整个大小具有如果它传递到功能被复制,而对于一个参考类型,只有参考(4字节)必须被复制。一个结构可能会节省一点时间,但因为你删除一个间接层,所以即使它是比这4个字节的,它仍然可能比周围传递引用更高效。但是,在某些时候,它变得如此之大,复制的成本变得明显。和拇指的一般规律是,这种情况通常发生约16个字节。 16选择,因为它是一个不错的轮数,二的幂和法可以是8(这是太小了,会使得结构几乎没用),或32(此时复制结构的成本已经是有问题的如果您使用的是结构性能方面的原因)

The point is that because value types are passed by value, the entire size of the struct has to be copied if it is passed to a function, whereas for a reference type, only the reference (4 bytes) has to be copied. A struct might save a bit of time though because you remove a layer of indirection, so even if it is larger than these 4 bytes, it might still be more efficient than passing a reference around. But at some point, it becomes so big that the cost of copying becomes noticeable. And a common rule of thumb is that this typically happens around 16 bytes. 16 is chosen because it's a nice round number, a power of two, and the alternatives are either 8 (which is too small, and would make structs almost useless), or 32 (at which point the cost of copying the struct is already problematic if you're using structs for performance reasons)

但最终,这就是性能的建议。它回答的问题:这将是最有效的使用?一个结构或类?。但它并没有回答。

But ultimately, this is performance advice. It answers the question of "which would be most efficient to use? A struct or a class?". But it doesn't answer the question of "which best maps to my problem domain".

结构和类的行为不同。如果你需要一个结构的行为,那么我会说,使之成为结构,事无大小。至少直到你遇到性能问题,配置您的code,并找到你的结构有问题。

Structs and classes behave differently. If you need a struct's behavior, then I would say to make it a struct, no matter the size. At least until you run into performance problems, profile your code, and find that your struct is a problem.

你的链接,甚至说,它是性能只是一个问题:

your link even says that it is just a matter of performance:

如果上述一项或多个条件   不满足,创建一个引用类型   代替的结构。未   恪守这一准则能   性能产生负面影响。

If one or more of these conditions are not met, create a reference type instead of a structure. Failure to adhere to this guideline can negatively impact performance.

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

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