有哪些“是”在C#中反射的性能特点? [英] What are the performance characteristics of 'is' reflection in C#?

查看:138
本文介绍了有哪些“是”在C#中反射的性能特点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显示是'为'铸造是远远快于前缀铸造,但关于什么是反思?有多糟糕呢?正如你可以想像,搜索是在谷歌是不是非常有效的。


解决方案

有几个选项:




  1. 经典投富富=(美孚)栏

  2. 转换运算符富富=酒吧为Foo

  3. 测试布尔是=酒吧美孚







  1. 经典投需要检查可以安全地转换为(快),然后真正做到这一点(慢),或者抛出一个异常(很慢)。

  2. 运营商需要检查可投,然后做演员,或者如果它不能安全地转换,那么它只是返回

  3. 运营商只是在检查看看可以转换为富,并返回一个布尔



测试是快,因为它只做一个完整的铸造操作的第一部分。在 运营商比传统铸铁更快,因为如果转换失败不抛出一个异常(这使得它很好的情况下,您合法预计,中投可能会失败)。



如果你只需要知道,如果变量然后使用 操作符, 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:

  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.

这篇关于有哪些“是”在C#中反射的性能特点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆