paseena
paseena

Reputation: 4315

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 valuetype structures? Thanks in advance

Upvotes: 0

Views: 114

Answers (3)

Jon Hanna
Jon Hanna

Reputation: 113282

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.

Upvotes: 0

Guffa
Guffa

Reputation: 700372

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.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941625

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.

Upvotes: 4

Related Questions