Java Reference
In-Depth Information
Solution
Use a profiler , or, time individual methods using System.currentTimeMillis() before and
after invoking the target method; the difference is the time that method took.
Discussion
Profilers
Profiling tools—profilers—have a long history as one of the important tools in a program-
mer's toolkit. A commercial profiling tool will help find bottlenecks in your program by
showing both the number of times each method was called, and the amount of time in each.
Quite a bit of useful information can be obtained from a Java application by use of the
JVisualVM tool, a standard part of the Oracle JDK. See Oracle's documentation on JavaVisu-
al VM . A newer tool that is part of the JDK as of JDK 7 Update 40 is Java Flight Recorder
profiler, a component of Java Mission Control . There are also third-party profilers that will
give more detailed information. NewRelic claims to have a powerful commercial perform-
ance analyzer.
Measuring one method
The simplest technique is to save the JVM's accumulated time before and after dynamically
loading a main program, and calculate the difference between those times. Code to do just
this is presented in Example 23-10 ; 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 isola-
tion. The overall time the program takes to run thus approximates the total time of many in-
vocations 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");
will probably work by creating a StringBuilder , appending the string "Time is " , the
value of n as a string, and " seconds" , and finally converting the finished StringBuilder
to a String and passing that to println() . Suppose you have a program that does a lot of
this, such as a Java servlet that creates a lot of HTML this way, and you expect (or at least
Search WWH ::




Custom Search