One Two Three
One Two Three

Reputation: 23517

Can the Java compiler eliminate dead code from the following scenario?

(Question #0 : Does the java compiler eliminate dead-code by default?)

Question #1: Suppose I have the following piece of code (which is artificially generated, so I don't have much control over), would the compiler be able to eliminate the dead-code for me?

static void foo(final Object o)
{
    if (o == null) {
        // do something
    }
    else {
        // do something

        if (o == null) { // this condition is never gonna be true
            // do something
        }
        else {
            // do something
        }
    }
}

Upvotes: 1

Views: 1637

Answers (1)

Jeffrey Bosboom
Jeffrey Bosboom

Reputation: 13663

javac (at least from OpenJDK) does not eliminate dead code, except for compile-time constant branches used to mimic other languages' conditional compilation (see the example at the end of this JLS section).

However, optimizing JVMs are very smart. HotSpot (the OpenJDK JIT) may or may not propagate a o != null constraint in this code, but it will notice via profiling that the inner o == null test is never true and avoid emitting code for that branch (turning it into an uncommon trap). And null checks that have always been observed false are really cheap because they're folded into load instructions, using segfaults to check for null; if null is ever seen, the JVM will look at the faulting instruction address to throw the NullPointerException from the right place, and will deoptimize to an explicit branch. (See more about HotSpot performance tricks here.) So even if it doesn't propagate the path constraint, it will effectively remove that branch anyway.

If you're concerned about runtime performance, you shouldn't worry about this at all, especially in the absence of profiling information indicating a problem.

If you just want small .class files, you should use an optimizer like ProGuard, though I don't know if it has the dataflow analysis necessary to optimize this particular pattern.

Upvotes: 2

Related Questions