有哪些“是”在C#中反射的性能特点? [英] What are the performance characteristics of 'is' reflection in C#?
问题描述
它显示是'为'铸造是远远快于前缀铸造,但关于什么是反思?有多糟糕呢?正如你可以想像,搜索是在谷歌是不是非常有效的。
有几个选项:
- 在经典投:
富富=(美孚)栏
- 在
为
转换运算符:富富=酒吧为Foo
- 在
是
测试:布尔是=酒吧美孚
- 在经典投需要检查
栏
可以安全地转换为富
(快),然后真正做到这一点(慢),或者抛出一个异常(很慢)。 - 在
为
运营商需要检查栏
可投,然后做演员,或者如果它不能安全地转换,那么它只是返回空
。 - 在
是
运营商只是在检查看看栏
可以转换为富,并返回一个布尔
。
的
是
测试是快,因为它只做一个完整的铸造操作的第一部分。在 为
运营商比传统铸铁更快,因为如果转换失败不抛出一个异常(这使得它很好的情况下,您合法预计,中投可能会失败)。
如果你只需要知道,如果变量栏
是富
然后使用 是
操作符, BUT ,如果你'重新去测试,如果栏
是富
,如果是这样,,然后将它转换 ,那么你应该使用 为
运营商。
基本上每投需要做的一个相当于是
内部检查与开始,以确保投是有效的。所以,如果你做了一个是
检查后接演(可以是为
投,或与经典的转换运算符)你实际上在做是
两次检查,这是一个轻微的额外的开销。
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.
这篇关于有哪些“是”在C#中反射的性能特点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!