[英]What will be the most performant and Why?
i just have a little design question. 我只是有一个小设计问题。
If i got this code 如果我收到此代码
public Interface Test
{
void Xyz();
}
public class1 : WebControl , Test
{
public void XyZ()
{
// do someting
}
public OnLoad()
{
((Test)this).Xyz();
// or
Test ctrl = this as Test;
ctrl.Xyz();
// or
Xyz();
}
}
Did the code will have a performance difference ? 代码是否会有性能差异? I think Xyz() direct call will be faster but i am not sure ((Test)this).Xyz() will have a difference with the direct call. 我认为Xyz()直接调用会更快,但我不确定((Test)this).Xyz()与直接调用会有区别。
What are your opinion about that, or reference documentation. 您对此有何看法或参考文档。
Thanks 谢谢
ps : I just whant have the difference performance, no answer with ... why you want to cast or specify the interface. ps:我只是想拥有不同的性能,没有答案。。。为什么要转换或指定接口。 I know i could just call directly my method 我知道我可以直接调用我的方法
I would hope that the compiler would remove both the cast and the "as" given that it can guarantee they will both succeed... and if that doesn't, the JIT may well do so. 我希望编译器会删除强制类型转换和“ as”,因为它可以保证它们都将成功...如果不是这样,JIT可能会这样做。 You would need the cast or as
operator if you used explicit interface implementation, mind you. 您需要演员或as
如果使用显式接口实现操作,介意你。 In that case I'd use a cast: I personally only use as
if it's feasible for the value to not be of the right type (in a situation other than a bug). 在这种情况下,我会使用一个转换:我个人只用as
如果它是可行的值不是正确的类型(不是一个bug等情况)的。
Ultimately any performance difference will be insignificant, but for readability's sake I'd just do without the cast where possible. 最终,任何性能差异都将是微不足道的,但是出于可读性考虑,我将尽可能不进行强制转换。
Call the method directly, there is no need to cast the this
reference to the interface type as the implementation of the method is still in the current class. 直接调用该方法,无需this
引用转换为接口类型,因为该方法的实现仍在当前类中。 If you cast the class to the interface type you are adding unnecessary indirection to get at a method that you have available to you. 如果将类强制转换为接口类型,则将添加不必要的间接访问,以获取可用的方法。
I don't think there would be a huge performance difference (as Jon points out, the JIT will most likely remove all casting as it is unnecessary) but for readability's sake just call the method directly. 我不认为会有很大的性能差异(正如Jon指出的那样,JIT很可能会删除所有的强制转换,因为这是不必要的),但是出于可读性的考虑,直接调用该方法即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.