9

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?

Jaanus Varus
  • 3,508
  • 3
  • 31
  • 49
  • http://stackoverflow.com/questions/1583050/performance-surprise-with-as-and-nullable-types – Jignesh.Raj May 20 '13 at 08:58
  • Thanks for the link, couldn't find it through search before. – Jaanus Varus May 20 '13 at 09:03
  • Interestingly, the accepted answer to [this SO question](http://stackoverflow.com/questions/2139798/why-is-the-c-sharp-as-operator-so-popular) recommends using `as`. – Matthew Watson May 20 '13 at 09:03
  • 1
    Just to say: the only scenario where I can get 10x / 15x performance delta is when using `as int?` - i.e. using a nullable type. For reference types, the difference between `is` / `as` is (by my measure) about 0.5 (multiple of), but keep in mind that is 0.5 of a **really really** small number – Marc Gravell May 20 '13 at 09:09

0 Answers0