1

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?

3
  • should be pretty simple to test that Commented Oct 13, 2015 at 7:39
  • 5
    en.wikipedia.org/wiki/Short-circuit_evaluation Commented Oct 13, 2015 at 7:40
  • OR operation will never check condition2 if condition1 is true. Commented Oct 13, 2015 at 7:44

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer Tagir. So are there any cases where an eager operation is preferred over a short circuit one?
@KiranR, actually I don't know such cases. FindBugs tries to report when non-short-circuit boolean expressions are detected and I don't remember that anybody complained that such report is false-positive (I'm a FindBugs contributor). Probably it was added in Java 1.0 just to be closer to C... Of course | for int/long type is very useful, but not for boolean.
-1

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.

1 Comment

apparently you didn't read the answer. compared to the other I wrote exactly the same. But without the reference to the spec.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.