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.
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.
Value types are usually more performant than reference types:
A reference type costs extra memory for the reference and performance when dereferencing
A value type does not need extra garbage collection. It gets garbage collected together with the instance it lives in. Local variables in methods get cleaned up upon method leave.
Value type arrays are efficient in combination with caches. (Think of an array of ints compared with an array of instances of type Integer
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With