Frage

Below are two snippets. Notice the ONE AND ONLY difference between the programs is that one break to return and the other return immediately. I understand it's good design practice to have one point of exit inside a method. But I am not worrying about design here. If I pay extra for using break, how much extra computation/memory/clock-cycle do I pay?

Program one:

public boolean doThis(String[] A){
  boolean indicator = false;
  for(int i=0; i<A.length; i++){
      if(A[i].equals("Taboo"))
        break;
      for(int x=0; x<=i; x++)
          //some work is done here. to make indicator true or false
  }
  return indicator;
}

Program two:

public boolean doThis(String[] A){
  boolean indicator = false;
  for(int i=0; i<A.length; i++){
      if(A[i].equals("Taboo"))
        return false;
      for(int x=0; x<=i; x++)
          //some work is done here. to make indicator true or false
  }
  return indicator;
}
War es hilfreich?

Lösung

If your compiler is any good, you pay a tiny bit less for the "return false" case.

You might be thinking that the "break" is expensive. With a crummy compiler, it is a single jump instruction that lands on the return. A good compiler will realize the jump is superflous, and can lift the return statement to the point of the break, if you don't mind expanding the code.

What makes the "return false" case slightly cheaper, is that "return indicator" may require a fetch from a memory to place the result in the calling-convention result-return register almost universally used by compilers. "return false" loads the constant into a register (in particular, the result-return register); this is always faster than fetch-from-memory on modern machines because the literal is embedded in the instruction stream, which the processor has already fetched.

A sophisticated compiler might keep all the variables in registers. In this case, "return indicator" may actually be faster, because a smart compiler may have schemed to place "indicator" in the result-return register; no work required to load the value. For the program you coded with a call on string equal, I doubt the compiler will try to keep all the variables in the registers; it would just have to expensively spill them all on the call to equal.

All this fine detail aside, this isn't the kind of thing you should worry about optimizing.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top