Java Reference
In-Depth Information
tion is much faster than the original one—simply because of the range checks at the begin-
ning of the method.
If, in the real world, users are only ever going to pass values less than 100 to the method,
then that comparison will give us the wrong answer. In the common case, the fibImpl()
method will be faster, and as Chapter 1 explained, we should optimize for the common case.
(This is obviously a contrived example, and simply adding a bounds test to the original im-
plementation makes it a better implementation anyway. In the general case, that may not be
possible.)
WHAT ABOUT A WARM-UP PERIOD?
One of the performance characteristics of Java is that code performs better the more it is ex-
ecuted, a topic that is covered in Chapter 4 . For that reason, microbenchmarks must include a
warm-up period, which gives the compiler a chance to produce optimal code.
The advantages and disadvantages of a warm-up period are discussed in depth later in this
chapter. For microbenchmarks, a warm-up period is required; otherwise, the microbenchmark is
measuring the performance of compilation rather than the code it is attempting to measure.
Taken all together, the proper coding of the microbenchmark looks like this:
package
package net . sdo ;
import
import java.util.Random
java.util.Random ;
public
public class
class FibonacciTest
FibonacciTest {
private
private volatile
volatile double
double l ;
private
private int
int nLoops ;
private
private int
int [] input ;
public
public static
void main ( String [] args ) {
FibonacciTest ft = new
static void
new FibonacciTest ( Integer . parseInt ( args [ 0 ]));
ft . doTest ( true
true );
ft . doTest ( false
false );
}
private
private FibonacciTest ( int
int n ) {
nLoops = n ;
input = new
int [ nLoops ];
Random r = new
new int
new Random ();
Search WWH ::




Custom Search