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.
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.
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.
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.
There are a few options:
Foo foo = (Foo)bar
as
cast operator: Foo foo = bar as Foo
is
test: bool is = bar is Foo
bar
can be safely cast to Foo
(quick), and then actually do it (slower), or throw an exception (really slow).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
.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 bar
is 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With