Jan 9 2012

Casting just a little faster

When choosing to cast in C#, there are at least two obvious patterns.

Explicit Casting

var foo = (Foo)instance;

‘as’ Keyword Casting

var foo = instance as Foo;

These two casting options have very different performance characteristics which should be considered. In tight loops you may wish to choose ‘as’ casting just for the performance benefits which I've measured as high as 50% over the alternative

Although this may seem like just a syntactic shortcut; under the covers; it’s actually two different sets of behaviors which account for the different costs

Explicit Casting

IL_0008:  castclass  Background_Activator_Test.Foo

‘as’ Keyword Casting

IL_000f:  isinst     Background_Activator_Test.Foo

Go on... Give it a go.

Tags:

Comments

1.
trackback DotNetKicks.com says:

Casting just a little faster

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Comments are closed