Java if optimization

I have the following statement:

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

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

Does it make sense to change the expressions inside the if?

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

Or does the compiler optimize for me?

+4
source share
5 answers

Note that two expressions do not have the same behavior if they foo()also have side effects .

If it controls the state of a program, it matters a lot if you always call it, or you call it only as a dependency on the value isEnabled.

For example, consider:

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

It matters if you always call foo(), or if you only call it when it is isEnabledturned on, as a result, the following two expressions are completely different from each other:

if (isEnabled && foo(arg)) { ...}  //local variable changes only if isEnabled==true
if (foo(arg) && isEnabled) { ...} //local variable always changes
+11
source

.

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

.

, , , isEnabled , foo(arg). .

+4

if?

. && , false. false, , .

+2

( ), .

, foo() , , . , , , .

:

int x = 0;

boolean foo(int arg) {
  x = arg;
  return x > 0;
}

void someMethod(int arg) {
  boolean isEnabled = false;
  if(foo(arg) && isEnabled) {
    //whatever  
  }

  //here you use x, I'll simply print it
  System.out.println("x=" + x);
}

void someOtherMethod(int arg) {
  boolean isEnabled = false;
  if(isEnabled && foo(arg)) {
    //whatever  
  }

  //here you use x, I'll simply print it
  System.out.println("x=" + x);
}

:

someOtherMethod(7); //foo(7) will not be called so x will still be 0
someMethod(5);    

x=0  
x=5 
+1

, Java ( java- -) . , , javac (, ).

Java ; JIT ( ).

, , , . . , foo() ( ); , , , foo() ?

, "foo()" ; , . , , ( ).

In other words: avoid microoptimization, see here to justify this recommendation.

+1
source

All Articles