Monday, 23 May 2011

Primitive Wrapper Classes and Their Factory Methods

The java SDK primitive wrapper classes such as Integer, Boolean and Long come with a whole bunch of often ignored factory methods that can be used to improve performance. Indeed, the best advice when converting a "true" or "false" is to use

      val = Boolean.valueOf("false");

rather than

      val = new Boolean("false");

The point this blog is not to espouse best practice, but to quantify the improvements available by using these factory methods. The code below creates a large number of Boolean objects comparing the time taken using Boolean.valueof against new Boolean(...).

  private static int LOOP_COUNT = 1000000;

    Boolean val = null;
   
long start = System.nanoTime();
   
for (int i = 0; i < LOOP_COUNT; i++) {
     
val = Boolean.valueOf("false");
   
}
   
long time1 = System.nanoTime() - start;

    System.out.println
("Spent " + time1 + "ns setting val to " + val
        +
" using a static factory");

    start = System.nanoTime
();
   
for (int i = 0; i < LOOP_COUNT; i++) {
     
val = new Boolean("false");
   
}
   
long time2 = System.nanoTime() - start;

    System.out.println
("Spent " + time2 + "ns setting val to " + val + " using new()");

    System.out.println
("Using 'new' takes " + (time2 - time1) + "ns longer, which is "
       
+ (time2 / time1) + "." + (time2 / (time2 % time1)) + " times longer. ");

The output from this code, run on my Mac Book, is not surprising but do underline best practice and a useful optimisation for your code.
Spent 13370000ns setting val to false using a static factory
Spent 49264000ns setting val to false using new()
Using 'new' takes 35894000ns longer, which is 3.5 times longer. 

No comments: