简体   繁体   English

Java编译器会优化手动转换以解决强制重载吗?

[英]Will the Java compiler optimize away casts for manual overload resolution?

Given the following code: 给出以下代码:

class C {
   static void m(String s) { ... } // 1
   static void m(Object o) { ... } // 2

   public static void main(String[] args) {
      m( (Object) "test"); // call m version 2
   }
}

Will the Java compiler optimize away the cast to Object i main, so that such "manual overload resolution" does not incur a performance overhead? Java编译器是否会优化对Object i main的强制转换,以便这种“手动重载解析”不会导致性能开销? Or will the actual runtime execution still perform the cast? 还是实际的运行时执行仍会执行强制转换?

That invocation is chosen at compile time. 该调用在编译时选择。 So it's not an optimisation so much as the compiler itself choosing which method to call. 因此,它不是优化,而是编译器自己选择要调用的方法。 The casting is there to aid the compiler and won't affect runtime performance. 强制转换在那里可以帮助编译器,并且不会影响运行时性能。

That's distinct from an override in which the object being called upon dictates the method at runtime eg 这与覆盖不同,在覆盖中,被调用的对象在运行时指定了方法,例如

shape.getArea(); // determined by whether shape is a square, circle etc.

If you write the above with/without the cast and generate the bytecode ( javap -verbose -c C ) you'll see this difference in the generated code: 如果使用/不使用javap -verbose -c C编写以上代码并生成字节码( javap -verbose -c C ),则会在生成的代码中看到以下差异:

<    2: invokestatic    #7; //Method m:(Ljava/lang/Object;)V
---
>    2: invokestatic    #7; //Method m:(Ljava/lang/String;)V

ie the compiler has simply chosen a different method ( const #7 will change in each case to reflect that differing method). 也就是说,编译器只是选择了一个不同的方法( const #7在每种情况下都会发生变化以反映该不同的方法)。

Exactly how much performance degradation are you worried about? 您担心多少性能下降? I'm curious as to what your circumstances are such that you think this may have any remotely noticeable effect, as I would never in a hundred years worry about this slowing down my app? 我对您的情况感到好奇,以为您认为这可能会产生任何明显的影响,因为一百年来我永远不会担心这会降低我的应用程序的速度?

Practically speaking: why not develop a benchmark app which runs both a cast and a direct invocation and see if you get any difference over a few million iterations? 从实践上讲:为什么不开发同时运行强制转换和直接调用的基准应用程序,看看在数百万次迭代中是否有任何区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM