简体   繁体   中英

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? 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:

<    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).

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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