I was reading through Jon Skeet's "C# in depth" second edition when I stumbled upon a paragraph in chapter "Nullable types":
SURPRISING PERFORMANCE TRAP I'd always assumed that doing one check would be faster than two, but it appears that's not the case - at least with the versions of .NET I've tested with. When writing a quick benchmark that summed all the integers within an array of type 'object[]' where only a third of the values were actually boxed integers, using 'is' and then a cast ended up being 20 times faster than using the 'as' operator.
On first sight, I thought that maybe the compiler is smart enough to optimize the double type check occured when using 'is' + cast, but it seems that is not the case. A .NET 4.0 code compiled with 32 bit compiler with the /OPTIMIZE flag turned on still resulted in two MSIL 'isinst' calls.
What might be the explanation of such dramatic performance difference for a case which intuitively should be the other way around?