开发者

Why does valutype take less space than object type in .NET?

It is said that valuetype derives from system.object. Why do object derived classes take more space than val开发者_运维百科uetype structures? Thanks in advance


Every object has an object header. That's 8 bytes on a 32-bit machine, 4 for the sync block and 4 for the type handle. A value type value only derives from System.Object when it is boxed. An int is 4 bytes when it unboxed, 12 bytes when it is boxed, +8 bytes for the header.

Check this answer to get more insight in what a boxed value type looks like.


Because value types are handled differently by the compiler. Eventhough they inherit from Object, they are not stored as objects.

Objects are stored on the heap, with an extra overhead of two pointers (8 bytes on a 32 bit system, 16 bytes on a 64 bit system). Value types are stored inline, either as part of an object, or in the stack frame of a method call, and there is no extra overhead.


There's a bit of a little white lie going on most of the time with regard to value types inheriting from ValueType and through that from Object. An unboxed int or bool doesn't have anything stored with it that relates to that inheritance. However, it gains it if it's boxed (which will happen implicitly with some operations). Most languages hide this so they simply appear to be the same as any other object that derives from Object whenever we use them as such, but also act as simple types when we use them as those.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜