Unexpected Performance Differences with "as" Operator and Nullable Types in C#
The "as" operator in C# provides a convenient way to perform type checks and casts dynamically. While it might seem that using "as" with nullable types would offer performance improvements over the traditional "is" operator and casting, recent tests have revealed surprising results.
In a test scenario where an object array contains a mix of integers, strings, and null references, the "as" operator significantly underperforms compared to the "is" operator. This was unexpected, as one would assume that the "as" operator's combination of type checking and value checking would be more efficient than querying dynamic types twice.
Analyzing the .NET implementation of "isinst" for nullable types reveals that it is not particularly slow. Instead, the issue appears to stem from the additional unboxing step required when using "as" with nullable types.
The JIT compiler can generate highly optimized code for the "is" operator and casting for non-nullable types. However, "as" with nullable types requires a more complex JIT helper function to perform the unboxing and conversion to Nullable
The LINQ solution, which uses "OfType()" and a cast to a generic type, also performs worse than the "is" operator. This could be attributed to the JIT helper function, JIT_Unbox(), that is called during the cast to Nullable
In conclusion, while the "as" operator provides a convenient syntax, it may not always offer the best performance when working with nullable types. In performance-critical scenarios, it is advisable to use the "is" operator and a cast directly to the desired type.
The above is the detailed content of Why is the C# 'as' operator slower than 'is' with nullable types?. For more information, please follow other related articles on the PHP Chinese website!