javaoptimizationoverloading

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?


Solution

  • 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 e.g.

    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
    

    i.e. the compiler has simply chosen a different method (const #7 will change in each case to reflect that differing method).