1

What are the differences between performing explicit casting and using as/is syntax?

// explicit casting
var castedObj = (ICar)originalObj;

// 'as' casting
var obj2 = originalObj as ICar;

My assumption is that using explicit casting is being optimized while creating the msil code while using as/is requires run-time checks which affect performance.

Am I correct?

VladL
  • 12,769
  • 10
  • 63
  • 83
Eran Sakal
  • 35
  • 4

3 Answers3

3

Performance should have nothing to do with your choice:

  • If you know it's an ICar, use a cast.

  • If you don't know, use "as" and test the result for null.

Use whichever expresses your intention.

Joe
  • 122,218
  • 32
  • 205
  • 338
1

The casting requires runtime checks too, so there's very little difference.

The as returns null or the casted object, so it may have the tiny extra overhead of assigning a reference [EDIT: But it seems not; see the blog linked below]

(If the compiler knows the type at compile time, it will optimise the cast away, but it will also optimise the as away. Also, if a cast fails it'll generate an exception which is very slow indeed, but not important if you expect the cast to always succeed.)

Technically, for a cast the IL produced is (for the example of casting object to string):

castclass string

and for an as:

isinst string

See the following blog post where someone has done some detailed timings (and found that isinst is marginally faster, but not by any amount that you'd care about):

http://m3mia.blogspot.co.uk/2007/11/comparing-isinst-to-castclass.html

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

Why don't you profile this and see for yourself?

An important thing to consider though is that in your first instance if it is not an ICar it will throw an exception. You could wrap that in a try/catch block and deal with the exceptions but it's likely quicker to use the 'as' keyword which will assign null to obj2 if originalobj is not an ICar, you can then simply do a null check rather than relying on the more computationally expensive exception handling.

However, on today's machines the difference in performance will be negligible.

Steve
  • 2,950
  • 3
  • 21
  • 32