Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java If optimization

Tags:

java

I do have the following statement:

isEnabled = false;
if(foo(arg) && isEnabled) {
 ....
}

public boolean foo(arg) {
  some really long running code
}

Does it make sense to swap the statements inside the if?

if(isEnabled && foo(arg)) { ... }

Or does the compiler the optimization for me?

like image 610
matthias Avatar asked Dec 01 '22 00:12

matthias


1 Answers

Note that the two expressions don't have the same behavior if foo() also has side effects.

If it is manipulating the state of the program, it makes a lot of difference if you always invoke it, or if you invoke it only as a dependency of the value of isEnabled.

For example, consider:

boolean foo(Object arg) { 
  someLocalVariable = arg;
  //do some calculation and return an answer
}

It matters if you always invoke foo(), or if you invoke it only in the case where isEnabled is turned on, resulting in the following two expressions to be completely different from each other:

if (isEnabled && foo(arg)) { ...}  //local variable changes only if isEnabled==true
if (foo(arg) && isEnabled) { ...} //local variable always changes
like image 154
amit Avatar answered Dec 23 '22 22:12

amit