C# 调用方法类/接口(本机代码、成本)
假设我们有一些实现某个接口 I 的类 A,
I i = new A();
i.method(); // example 1
A a = (A)i;
a.method() // example 2
每次调用“method()”生成的 IL 代码是相同的,但哪一个对方法“method()”的调用在本机代码中成本更高,为什么?
任何帮助将不胜感激。
Suppose we have some class A that implements some interface I
I i = new A();
i.method(); // example 1
A a = (A)i;
a.method() // example 2
The IL code generated for each call to "method()" is same, but which one of invocations to method "method()" have more cost in native code and why?
Any help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 IL 代码相同,则本机代码(的成本)也会相同。为什么 JIT 会以不同的方式对待他们?
If the IL code is the same, so will the (cost of) the native code. Why would the JIT treat them differently?
一般来说,对
((A)a).method()
的调用会(稍微)更快,因为 JIT 编译器(静态)知道应该调用的具体方法,因此可以直接调用A.method
。通过接口 I 调用它需要对引用指向的对象的实际类型进行运行时检查,然后分派到该实现。不过,我没有任何参考资料。我确实知道 Java JIT 编译器在这方面进行了一些优化,因为每个方法调用都是虚拟的 - 它猜测&缓存特定接口方法最常用的实现并针对这种情况进行优化。 .NET JIT 几乎不需要这个,因为方法必须是显式虚拟的。
这是非常的一个微优化案例,您确实不应该担心。
Generally, the call to
((A)a).method()
will be (ever so slightly) quicker, as the JIT compiler knows (statically) the concrete method that should be called, and so can callA.method
directly. Calling it through the interfaceI
requires a runtime check on the actual type of object that the reference points to, and then dispatch to that implementation. I don't have any references for that, though.I do know that the Java JIT compiler has got some optimizations in this regard, as every method call is virtual - it guesses & caches the most-used implementation of a particular interface method and optimizes for that case. The .NET JIT doesn't need this nearly as much, as methods have to be explicitly virtual.
This is very much a case of micro-optimization that you really shouldn't be worrying about.