Search code examples
c#pass-by-referencepass-by-valuevalue-typereference-type

Benefit of Value Types over Reference Types?


Seeing as new instances of value types are created every time they are passed as arguments, I started thinking about scenarios where using the ref or out keywords can show a substantial performance improvement.

After a while it hit me that while I see the deficit of using value types I didn't know of any advantages.
So my question is rather straight forward - what is the purpose of having value types? what do we gain by copying a structure instead of just creating a new reference to it?

It seems to me that it would be a lot easier to only have reference types like in Java.

Edit: Just to clear this up, I am not referring to value types smaller than 8 bytes (max size of a reference), but rather value types that are 8 bytes or more.

For example - the Rectangle struct that contains four int values.


Solution

    • An instance of a one-byte value type takes up one byte. A reference type takes up the space for the reference plus the sync block and the virtual function table and ...

    • To copy a reference, you copy a four (or eight) byte reference. To copy a four-byte integer, you copy a four byte integer. Copying small value types is no more expensive than copying references.

    • Value types that contain no references need not be examined by the garbage collector at all. Every reference must be tracked by the garbage collector.