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.
There are a few options:
- The classic cast:
Foo foo = (Foo)bar
- The
as
cast operator:Foo foo = bar as Foo
- The
is
test:bool is = bar is Foo
- The classic cast needs to check if
bar
can be safely cast toFoo
(quick), and then actually do it (slower), or throw an exception (really slow). - The
as
operator needs to check ifbar
can be cast, then do the cast, or if it cannot be safely cast, then it just returnsnull
. - The
is
operator just checks ifbar
can be cast to Foo, and return aboolean
.
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.
The way I learned it is that this:
if (obj is Foo) {
Foo f = (Foo)obj;
f.doSomething();
}
is slower than this:
Foo f = obj as Foo;
if (f != null) {
f.doSomething();
}
Is it slow enough to matter? Probably not, but it's such a simple thing to pay attention for, that you might as well do it.
"is" is basically equivalent to the "isinst" IL operator -- which that article describes as fast.
It should be quick enough to not matter. If you are checking the type of an object enough for it to make a noticeable impact on performance you need to rethink your design
© 2022 - 2024 — McMap. All rights reserved.