Performance Timing


You need to know how long a Java program takes to run.


Call System.currentTimeMillis( ) before and after invoking the target class dynamically.


The simplest technique is to save the JVM’s accumulated time before and after dynamically loading a main program, and calculating the difference between those times. Code to do just this is presented in Example 25-7; for now, just remember that we have a way of timing a given Java class.

One way of measuring the efficiency of a particular operation is to run it many times in isolation. The overall time the program takes to run thus approximates the total time of many invocations of the same operation. Gross numbers like this can be compared if you want to know which of two ways of doing something is more efficient. Consider the case of string concatenation versus println( ). The code:

println("Time is " + n.toString(  ) + " seconds");

creates a StringBuffer, appends the string "Time is ", the value of n as a string, and " seconds", and finally converts the finished StringBuffer to a String and passes that to println( ). Suppose you have a program that does a lot of this, such as a Java servlet (see Chapter 18) that creates a lot of HTML this way, and you expect (or at least hope) that your web site will be sufficiently busy that doing this efficiently will make a difference. There are two ways of thinking about this:

  • Theory A: This string concatenation is inefficient.

  • Theory B: String concatenation ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.