Search code examples
javaautoboxing

Boolean_val vs Boolean.TRUE(Boolean_val) when used in a conditional statement


In (1.8+) is there a performance difference between the following 2 if statements. My code has to make a lot of these types of calls in iteration.

void test(final Boolean val) {
    if (val) {
        ...
    }
}

and

void test(final Boolean val) {
    if (Boolean.TRUE.equals(val) {
        ...
    }
}

Will the JIT compiler optimize away the difference? Is the unboxing more expensive than the equals method call?


Solution

  • The unboxing is equal to val.booleanValue(), so the JIT should be able to inline such method.

    The Boolean.TRUE.equals(val) looks better is the sense of null-safety, because autoboxing on null-value will cause a NullPointerException.

    See also: