Java Reflection Performance

前端 未结 14 1627
感动是毒
感动是毒 2020-11-22 08:25

Does creating an object using reflection rather than calling the class constructor result in any significant performance differences?

14条回答
  •  长发绾君心
    2020-11-22 09:10

    Yes there is a performance hit when using Reflection but a possible workaround for optimization is caching the method:

      Method md = null;     // Call while looking up the method at each iteration.
          millis = System.currentTimeMillis( );
          for (idx = 0; idx < CALL_AMOUNT; idx++) {
            md = ri.getClass( ).getMethod("getValue", null);
            md.invoke(ri, null);
          }
    
          System.out.println("Calling method " + CALL_AMOUNT+ " times reflexively with lookup took " + (System.currentTimeMillis( ) - millis) + " millis");
    
    
    
          // Call using a cache of the method.
    
          md = ri.getClass( ).getMethod("getValue", null);
          millis = System.currentTimeMillis( );
          for (idx = 0; idx < CALL_AMOUNT; idx++) {
            md.invoke(ri, null);
          }
          System.out.println("Calling method " + CALL_AMOUNT + " times reflexively with cache took " + (System.currentTimeMillis( ) - millis) + " millis");
    

    will result in:

    [java] Calling method 1000000 times reflexively with lookup took 5618 millis

    [java] Calling method 1000000 times reflexively with cache took 270 millis

提交回复
热议问题