Eliminating dead-code and constant folding

Dead-code and constant folding are often referred to as redundant code and our modern compilers are pretty good at eliminating them. An example of dead-code is code that will never be reached. Consider the following example:

. . .
int value = 10;
if (value != null) {
System.out.println("The value is " + value + ".");
} else {
System.out.println("The value is null."); // This is a line of Dead-Code
}
. . .

In our preceding example, the line identified as dead-code is never reached since the variable value will never be equal to null. It is set to 10 immediately before the conditional if statement evaluates the variable.

The problem is that benchmarking code can sometimes be removed in the attempt to eliminate dead-code.

Constant folding is the compiler operation that occurs when compile-time constraints are replaced with actual results. The compiler performs constant folding to remove any redundant runtime computations. In the following example, we have a final int followed by a second int based on a mathematical calculation involving the first int:

. . .
static final int value = 10;
int newValue = 319 * value;
. . .

The constant folding operation would convert the two lines of the preceding code to the following:

int newValue = 3190;

There is one suggested strategy for this pitfall:

  • Use the JMH API support to ensure your benchmarking code is not eliminated
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset