diaries, triumphs, failures, and rants

pageicon Thursday Apr 30, 2009

Mutability, class creation, singletons, and performance

It is possible to slice off a lot of execution time in Java code by looking for instances where classes can be converted to immutable, singleton classes. This seems obvious on the face of it, yet I wanted proof. Here is a class that exercises a created object versus a singleton object:


import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;


public final class ObjectCreationTest {

  interface Objects {}

  static final class MustBeCreated implements Objects {
  }

  static final class Singleton implements Objects {
    public static Singleton getInstance() {
      if(instance == null) {
        instance = new Singleton();
      }
      return instance;
    }
    private static Singleton instance = null;
    private Singleton() {}
  }

  public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(new Option("n",true,"numberOfIterations"));

    PosixParser parser              = new PosixParser();
    CommandLine commandLine         = parser.parse(options,args);
    String sIterations              = commandLine.getOptionValue('n');
    Integer iterations;
    if(sIterations != null) {
      iterations = Integer.parseInt(sIterations);
    } else {
      iterations = 1024;
    }


    // iterate, creating MustBeCreated objects
    long t0 = System.currentTimeMillis();
    for(int i = 0; i < iterations; ++i) {
      Objects object = new MustBeCreated();
    }
    System.out.printf("Elapsed time: %d ms%n",System.currentTimeMillis()-t0);

    // iterate, getting Singleton objects
    t0 = System.currentTimeMillis();
    for(int i = 0; i < iterations; ++i) {
      Objects object = Singleton.getInstance();
    }
    System.out.printf("Elapsed time: %d ms%n",System.currentTimeMillis()-t0);
  }
}

This simple class iterates over a number of iterations, one set to create a class, and another set to use the singleton pattern Here are the results:

CLASSPATH="$HOME"/lib/commons-cli-1.2.jar javac -g ObjectCreationTest.java 
/Users/terrygardner $ CLASSPATH=.:"$HOME"/lib/commons-cli-1.2.jar java ObjectCreationTest -n 100000000
Elapsed time: 1208 ms
Elapsed time: 4 ms
/Users/terrygardner $ CLASSPATH=.:"$HOME"/lib/commons-cli-1.2.jar java ObjectCreationTest -n 100000000
Elapsed time: 1212 ms
Elapsed time: 6 ms
/Users/terrygardner $ CLASSPATH=.:"$HOME"/lib/commons-cli-1.2.jar java ObjectCreationTest -n 100000000
Elapsed time: 1216 ms
Elapsed time: 5 ms
/Users/terrygardner $ 
The results are pretty clear; the singleton executes in constant time, whereas the creation is a bit worse. The lesson here is look for places where classes can be final and immutable singletons.
Comments:

Wow what an amazing discovery. Object creation cost more than a method call. Not to mention that making a class final does not make it immutable but simple non-extendable - i.e no subclasses.

You probably meant:
class ImmutableObject {
private final int value;
ImmutableObject(int value){ this.value = value; }
}

Which is a class that when constructed has an immutable property "value".

Posted by James on April 30, 2009 at 05:32 PM EDT #

Not so much an amazing discovery as a reminder to myself. Your point is well-taken, though.

Posted by Terry Gardner on May 01, 2009 at 07:04 AM EDT #

Post a Comment:
Comments are closed for this entry.

« November 2009
SunMonTueWedThuFriSat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
     
       
Today

Feeds

Search this blog

Links

Weblog menu

Today's referrers

Today's Page Hits: 165