Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the performance characteristics of 'is' reflection in C#? [duplicate]

Tags:

It's shown that 'as' casting is much faster than prefix casting, but what about 'is' reflection? How bad is it? As you can imagine, searching for 'is' on Google isn't terribly effective.

like image 524
Ben Collins Avatar asked Sep 11 '08 21:09

Ben Collins


People also ask

Why do we need reflection in c#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Is reflection still slow C#?

Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations.

Is reflection API slow?

Adding setAccessible(true) call makes these reflection calls faster, but even then it takes 5.5 nanoseconds per call. Reflection is 104% slower than direct access (so about twice as slow). It also takes longer to warm up.


1 Answers

There are a few options:

  1. The classic cast: Foo foo = (Foo)bar
  2. The as cast operator: Foo foo = bar as Foo
  3. The is test: bool is = bar is Foo

  1. The classic cast needs to check if bar can be safely cast to Foo (quick), and then actually do it (slower), or throw an exception (really slow).
  2. The as operator needs to check if bar can be cast, then do the cast, or if it cannot be safely cast, then it just returns null.
  3. The is operator just checks if bar can be cast to Foo, and return a boolean.

The is test is quick, because it only does the first part of a full casting operation. The as operator is quicker than a classic cast because doesn't throw an exception if the cast fails (which makes it good for situations where you legitimately expect that the cast might fail).

If you just need to know if the variable baris a Foo then use the is operator, BUT, if you're going to test if bar is a Foo, and if so, then cast it, then you should use the as operator.

Essentially every cast needs to do the equivalent of an is check internally to begin with, in order to ensure that the cast is valid. So if you do an is check followed by a full cast (either an as cast, or with the classic cast operator) you are effectively doing the is check twice, which is a slight extra overhead.

like image 90
Daniel Fortunov Avatar answered Sep 21 '22 19:09

Daniel Fortunov