In java (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?
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:
Boolean
class in Java 10 in the OpenJDK project.