I’m using Java but I guess this question applies to whatever language. I just want to ask whether it’s better practice to exit a loop using a boolean which I toggle within the loop or to just use break;
For example, I was just writing a method to get the valid moves for a Queen in chess.
private static final int[][] DIRS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {-1, 1}, {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, y, newX, newY));
stopped = true;
}
}
}
}
return validMoves;
}
If I exit the while loop using break; instead of setting stopped to true like I do it’s my understanding that it runs more efficiently but is not the greatest code style.
Performance-wise, it won’t matter much, you are allocating 1 boolean on the stack and adding 1 comparison at each loop iteration, so nothing to worry about.
It mainly depends on whether you want to finish executing the rest of the loop code before exiting it or not. Break will exit immediatly and setting a boolean will wait for the next iteration before stopping.
If you don’t need to finish the loop iteration, your code will be easier to read if you use
break