问题描述
我有一个需要快速性能的程序.在它的一个内部循环中,我需要测试一个对象的类型,看它是否继承自某个接口.
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 的内置类型检查功能.最优雅的方法可能是is"关键字:
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() 函数,该函数返回一个预定义的枚举值(在我的情况下,实际上,我只需要一个 bool).这种方法会很快,但不太优雅.
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.
我听说有一个专门针对is"关键字的 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?
更新:感谢所有知情的回答!答案中似乎有几个有用的观点:安德鲁关于是"自动执行演员的观点是必不可少的,但 Binary Worrier 和 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.
推荐答案
使用 is
会损害性能,如果检查类型后,就强制转换为该类型.is
实际上将对象转换为您正在检查的类型,因此任何后续转换都是多余的.
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#“是"运算符的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!