I’ve been trying to understand this paragraph, but somehow I couldn’t virtualize it in my mind, some one please elaborate it little bit:
Unboxing is not the exact opposite of boxing. The unboxing operation
is much less costly than boxing. Unboxing is really just the operation
of obtaining a pointer to the raw value type (data fields) contained
within an object. In effect, the pointer refers to the unboxed portion
in the boxed instance. So, unlike boxing, unboxing doesn’t involve the
copying of any bytes in memory. Having made this important
clarification, it is important to note that an unboxing operation is
typically followed by copying the fields.Richter, Jeffrey (2010-02-05). CLR via C# (Kindle Locations
4167-4171). OReilly Media – A. Kindle Edition.
In order to box an int you need to create an object on the heap large enough to hold all of the data that the struct holds. Allocating a new object on the heap means work for the GC to find a spot, and work for the GC to clean it up/move it around during and after its lifetime. These operations, while not super expensive, aren’t cheap either.
To unbox a value type all you’re doing is de-reference the pointer, so to speak. You simply need to look at the reference (which is what the
objectyou have is) to find the location of the actual values. Looking up a value in memory is very cheap, which is why that paragraph is saying ‘unboxing’ is cheap.Update:
While an unboxed value type will usually be copied to some other location right after being unboxed, that isn’t always the case. Consider the following example:
The
MyStructis boxed intoobjbut when it’s unboxed it’s never copied anywhere, a method is simply invoked on it. LIkewise you could pull a property/field out of the struct and copy just that part of it without needing to copy the whole thing. This might look a bit contrived, but it’s still not entirely absurd. That said, as your quote implies, it’s still likely to copy the struct after you unbox it.