Performance surprise with "as" and nullable types
Clearly the machine code the JIT compiler can generate for the first case is much more efficient. One rule that really helps there is that an object can only be unboxed to a variable that has the same type as the boxed value. That allows the JIT compiler to generate very efficient code, no value conversions have to be considered.
The is operator test is easy, just check if the object isn't null and is of the expected type, takes but a few machine code instructions. The cast is also easy, the JIT compiler knows the location of the value bits in the object and uses them directly. No copying or conversion occurs, all machine code is inline and takes but about a dozen instructions. This needed to be really efficient back in .NET 1.0 when boxing was common.
Casting to int? takes a lot more work. The value representation of the boxed integer is not compatible with the memory layout of Nullable<int>
. A conversion is required and the code is tricky due to possible boxed enum types. The JIT compiler generates a call to a CLR helper function named JIT_Unbox_Nullable to get the job done. This is a general purpose function for any value type, lots of code there to check types. And the value is copied. Hard to estimate the cost since this code is locked up inside mscorwks.dll, but hundreds of machine code instructions is likely.
The Linq OfType() extension method also uses the is operator and the cast. This is however a cast to a generic type. The JIT compiler generates a call to a helper function, JIT_Unbox() that can perform a cast to an arbitrary value type. I don't have a great explanation why it is as slow as the cast to Nullable<int>
, given that less work ought to be necessary. I suspect that ngen.exe might cause trouble here.
It seems to me that the isinst
is just really slow on nullable types. In method FindSumWithCast
I changed
if (o is int)
to
if (o is int?)
which also significantly slows down execution. The only differenc in IL I can see is that
isinst [mscorlib]System.Int32
gets changed to
isinst valuetype [mscorlib]System.Nullable`1<int32>