开发者

Does the CLR store small values in 'natural' sized locations?

In Java, a byte or short is st开发者_StackOverflow社区ored in the JVM's 'natural' word length, i.e. for the most part, 32-bits. An exception would be an array of bytes, where each byte occupies a byte of memory.

Does the CLR do the same thing?

If it does do this, in what situations are there exceptions to this? E.g. How much memory does this occupy?

struct MyStruct
{
    short s1;
    short s2;
}


Although it's not really intended for this purpose, and may at times give slightly different answers (because it's thinking about things from a Marshalling point of view, not a CLR internal structures point of view), Marhsal.SizeOf can give an answer:

System.Runtime.InteropServices.Marshal.SizeOf(typeof(MyStruct))

In this case, it answers 4. (i.e. the shorts are being stored as shorts). Please note that this is an implementation detail, so the answer today should not be relied upon for any purpose.


It is actually the job of the JIT compiler to assign the memory layout of classes and structures. The actual layout is not discoverable in any way (beyond looking at the generated machine code), a [StructLayout] attribute is required to marshal the object to a known layout. The JIT takes advantage of this by re-ordering fields to keep them aligned and minimize the allocation size.

There will be no surprises in the struct you quoted, the fields are already aligned on any current CPU architecture that can execute managed code. The size of value types is guaranteed by the CLI, a short always takes 16 bits. Your structure will take 32 bits.


The CLR does to some extent pack members of the same size. It does pack arrays, and I would expect your example structure to take up four bytes on any platform.

Exactly which types are packed and how depends on the CLR implementation and the current platform. The rules are not strictly defined, so that the CLR has some freedom to rearrange the members to store them in the most efficient manner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜