I'd like to know how Java would handle the following scenario:
Suppose I have a class called Debug, which looks like this:
public class Debug
{
private static final boolean isAssertEnabled = true;
public static void assertTrue(boolean b, String errorMessage) {
if (isAssertEnabled) {
if (!b) {
throw new RuntimeException(errorMessage);
}
}
}
}
and suppose my code has a call that looks something like this:
...
Debug.assertTrue((x + y != z) && (v - u > w), "Some error message");
....
I have a few questions:
Thanks for you help!
The quickest way to find dead code is to use a good IDE. Delete unused code and unneeded files. In the case of an unnecessary class, Inline Class or Collapse Hierarchy can be applied if a subclass or superclass is used. To remove unneeded parameters, use Remove Parameter.
In some areas of computer programming, dead code is a section in the source code of a program which is executed but whose result is never used in any other computation. The execution of dead code wastes computation time and memory.
A dead code is just a warning message native to Eclipse or another compiler. It is not displayed in the javac core java compiler. On the other hand, the unreachable code is an error reported by the javac Java compiler. It is officially included in java as an error.
In Eclipse, "dead code" is code that will never be executed. Usually it's in a conditional branch that logically will never be entered. A trivial example would be the following: boolean x = true; if (x) { // do something } else { // this is dead code! }
Why are you trying to build what Java already provides natively?
The assert
keyword does exactly what you want: its execution can be turned on and off (on a per-package level) and the evaluation of the boolean expression is avoided when assertions are disabled.
The evaluation of the boolean expression should not be compiled away - at least by javac.
Even if the Debug
class file currently do nothing with the value, who's to say that that will be the case at execution time?
After making the Debug class compile (by making isAssertEnabled
static), javac still includes the code - but I would expect the JIT compiler to remove it (although you should see the question Peter referenced). Whether it could then inline the method to nothing, I'm not sure. Again, if the JIT compiler could do that, and if it realized that evaluating the arguments couldn't have any side-effects, it could potentially avoid the evaluation. I wouldn't personally write code depending on that though.
That reminds me of Log4j's "isTraceEnabled()", "isDebugEnabled()", and so on. Have to explicitly wrpa your log statements in if-statements to avoid unnecassary log statement evaluations.
if(logger.isDebugEnabled() {
logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
}
see here under "Performance"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With