There is no information on what is actually going on below the belt. Take a look at this example:
object o = "test"; if (o is string) { var x = (string) o; }
This means the following IL:
IL_0000: nop IL_0001: ldstr "test" IL_0006: stloc.0 // o IL_0007: ldloc.0 // o IL_0008: isinst System.String IL_000D: ldnull IL_000E: cgt.un IL_0010: stloc.1 IL_0011: ldloc.1 IL_0012: brfalse.s IL_001D IL_0014: nop IL_0015: ldloc.0 // o IL_0016: castclass System.String IL_001B: stloc.2 // x IL_001C: nop IL_001D: ret
The calls to isinst and castclass are important castclass - and relatively expensive. If you compare this to an alternative, you will see that the isinst check isinst runs:
object o = "test"; var oAsString = o as string; if (oAsString != null) { } IL_0000: nop IL_0001: ldstr "test" IL_0006: stloc.0
It's also worth mentioning that the value type will use unbox.any rather than castclass :
object o = 5; if (o is int) { var x = (int)o; } IL_0000: nop IL_0001: ldc.i4.5 IL_0002: box System.Int32 IL_0007: stloc.0
Please note that this does not necessarily lead to a faster result, as we can see here . It seems that there have been improvements since this question was asked, though: it seems that the castes execute as fast as before, but as and linq now about 3 times faster.
Jeroen Vannevel Apr 05 '16 at 15:11 2016-04-05 15:11
source share