Exit loop in Java
I'm using Java, but I think this problem applies to any language I just want to ask, it is better to use Boolean value to exit the loop. I switch or only use break in the loop;
For example, I'm just writing a way to get the Queen's effective action in chess
private static final int[][] DIRS = {{0,1},{0,-1},{1,0},{-1,-1}}; public Vector<Move> getValidMoves() { Vector<Move> validMoves = new Vector<Move>(); for (int i = 0; i < DIRS.length; i++) { boolean stopped = false; int newX = x + DIRS[i][0]; int newY = y + DIRS[i][1]; while (!stopped && newX >= 0 && newX < 8 && newY >= 0 && newY < 8) { if (board[newX][newY] == null) { validMoves.add(new Move(x,y,newX,newY)); newX += DIRS[i][0]; newY += DIRS[i][1]; } else { if (board[newX][newY].getColour() == colour) { stopped = true; } else { validMoves.add(new Move(x,newY)); stopped = true; } } } } return validMoves; }
If I use break to exit the while loop; Instead of setting stop to true like I do, it's my understanding that it runs more effectively, but not the best code style
Solution
In terms of performance, it doesn't matter. You allocate a Boolean value on the stack and add a comparison at each loop iteration, so there's nothing to worry about
It mainly depends on whether you want to complete the remaining loop code before exiting Break will exit immediately and set a Boolean value. It will wait for the next iteration before stopping
If you don't need to complete the loop iteration, your code will be easier to read if you use break