August 25, 2004

Performance Comparison Between Operator new and method Class.newInstance()

One of the projects I'm working on is using a DAO pattern for accessing database and for creating data wrappers of table records. Because of the design, we were forced to subclass a DAO class every time we created a new data class. While it would be easy to change the design to accept a Class object as a parameter that would specify the data type, we hesitated at first because of performance considerations. In many cases we would need to instantiate thousands of objects.

So I made a quick test to compare the performance of creating objects with operator new to creating them with a call to newInstance() of a Class object. It turned out that creating a million String objects took 143 milliseconds with new and 284 milliseconds with newInstance. Not bad at all, absolutely nothing to worry about. This was with 1.4.2 Java. I was actually very (positively) surprised of the performance of Java, considering that using newInstance() requires both a try-catch block and a typecast. A typecast is there because you can't really do much with the object without it.


public static class Test extends TestCase {
  private static final Logger log = Logger.getLogger(Test.class.getName() );

  public void testNewAndNewInstancePerformance() {
    long milliseconds = (new Date() ).getTime();
    for (int i = 0; i < 1000000; i++) {
      String string = new String();
      String string2 = string;
    }
    log.info("Strings created with new, took " + ( (new Date() ).getTime() - milliseconds) + " milliseconds");

    milliseconds = (new Date() ).getTime();
    for (int i = 0; i < 1000000; i++) {
      try {
        Object obj = String.class.newInstance();
        String string = (String)obj;
      } catch (Exception e) {}
    }
    log.info("Strings created with newInstance(), took " + ( (new Date() ).getTime() - milliseconds) + " milliseconds");

  }
}

Posted by thoughts at August 25, 2004 08:27 AM | TrackBack
Comments

mmmm... interesting find.. however the ratio is almost 2ice.. thats not very encouraging is it?

Posted by: Ryan at April 16, 2005 04:57 AM
Post a comment









Remember personal info?