Kiran
Kiran

Reputation: 49

What is the level of optimization of the java compiler?

So lets consider this following statement that executes more than a million times inside a loop.

boolean validity = condition1 || condition2;

It is safe to assume that both condition1 and condition2 have very complex calculation inside them. So since there is an OR operator here, I assume it would be wise to separately check for condition1 first and then if necessary, condition2 afterwards like,

boolean validity = condition1;
if( !validity )
    validity = condition2;

Should I manually perform optimizations like this or does the java compiler automatically takes care of these things?

Upvotes: 1

Views: 107

Answers (2)

Tagir Valeev
Tagir Valeev

Reputation: 100139

As Java Language Specification, §15.24 says:

The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.

Thus it's required by language specification that the right part is evalutated only if left part is false. It's not an optimization, it's a part of language. Optimizations are not the part of language specification, they may make your code faster, but they should never make your code to behave differently. Here however the behavior would be different if both parts were evaluated as the right part might have a side-effect.

Upvotes: 8

Robert Franz
Robert Franz

Reputation: 543

The java compiler is capable to execute the function for condition1 at first. When it is true then the function for condition2 is not executed any longer. So the optimization is not required. This is as there is an OR-Operation.

Upvotes: -1

Related Questions