C#“是”经营者业绩 [英] C# 'is' operator performance

查看:98
本文介绍了C#“是”经营者业绩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要快速的性能的程序。在其内部循环中的一个,我需要测试一个对象的类型,看它是否从某个接口继承。

I have a program that requires fast performance. Within one of its inner loops, I need to test the type of an object to see whether it inherits from a certain interface.

要做到这一点是用CLR的内置类型检查的功能的一种方式。最优雅的方式有可能作为'是'关键字:

One way to do this would be with the CLR's built-in type-checking functionality. The most elegant method there probably being the 'is' keyword:

if (obj is ISpecialType)

另一种方法是给基类的我自己的虚拟的GetType()函数返回一个pre定义枚举值(在我的情况,其实,我只需要一个布尔)。这方法是快,但不太优雅。

Another approach would be to give the base class my own virtual GetType() function which returns a pre-defined enum value (in my case, actually, i only need a bool). That method would be fast, but less elegant.

我听说没有为'是'关键字的IL指令明确,但这并不意味着翻译成当地组装它执行快。任何人都可以分享一些洞察的表现'是'与其他的方法?

I have heard that there is an IL instruction specifically for the 'is' keyword, but that doesn't mean it executes fast when translated into native assembly. Can anyone share some insight into the performance of 'is' versus the other method?

更新:感谢所有的通知答案!这似乎是一个有用的几个点有s $ P $垫出答案之中:安德鲁的约是自动执行施法点是必不可少的,而是由二进制杞人忧天和Ian收集的性能数据也是非常有用的。如果其中一个答案进行了编辑,包括这将是巨大的所有的这些信息。

UPDATE: Thanks for all the informed answers! It seem a couple helpful points are spread out among the answers: Andrew's point about 'is' automatically performing a cast is essential, but the performance data gathered by Binary Worrier and Ian is also extremely useful. It would be great if one of the answers were edited to include all of this information.

推荐答案

使用如果,一旦你选中的类型,你施放该类型可以影响性能。 实际上注塑对象要检查,所以任何随后的铸造是多余的类型。

Using is can hurt performance if, once you check the type, you cast to that type. is actually casts the object to the type you are checking so any subsequent casting is redundant.

如果您打算无论如何要投,这里是一个更好的方法:

If you are going to cast anyway, here is a better approach:

ISpecialType t = obj as ISpecialType;

if (t != null)
{
    // use t here
}

这篇关于C#“是”经营者业绩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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