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

4

21

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.

Herbivore answered 11/9, 2008 at 21:25 Comment(1)
I realize that date isn't the only determining factor in closing duplicate questions, but my question was posted and answered and upvoted all before the other question was posted. It is the duplicate, not this one.Herbivore
M
20

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.

Myrtismyrtle answered 11/9, 2008 at 22:39 Comment(1)
The check is the slowest, the cast is very fast on reference types, because it just returns the reference.Aguilera
T
8

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.

Th answered 11/9, 2008 at 21:32 Comment(0)
A
6

"is" is basically equivalent to the "isinst" IL operator -- which that article describes as fast.

Abutting answered 11/9, 2008 at 21:27 Comment(0)
L
2

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

Locomotive answered 11/9, 2008 at 21:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.