There are two points, the question of the if
and the question of the additional point of saliency the if
, with aspects of performance and readability.
Performance
In any case, it seems related to the loop unrolling technique.
In short, a processor does not execute an instruction in only one phase, but in several. So, to improve the performance, it is "advancing work" and begins to work on the following instructions before finishing the ones already in progress 1 . In addition, there are other dependencies (an instruction needs data that calculates a previous instruction).
This causes problems with the jumps, because the processor does not know which instruction will be executed. One usually chooses to choose one of the possible options and, if it turns out that it is not fulfilled, "eliminate" the half-executed instructions 2 , but it supposes a loss of performance.
One of the options is to try to make predictions based on previous performance 3 , but there are auxiliary techniques and one of them is the loop unrolling .
This is based on "unroll" the loop and have each iteration programmed as several. For example
for(int i = 0; i < miArray.size; i++) {
acumulado += miArray[i];
}
really just become:
for(int i = 0; i < (miArray.size /3) * 3; i = i+3) {
acumulado += miArray[i];
acumulado2 += miArray[i + 1];
acumulado3 += miArray[i + 2];
}
acumulado += acumulado2 + acumulado3;
more additional code to deal with the latest array data.
This not only reduces the number of hops, but also gives the compiler more freedom to rearrange the instructions so that the data dependencies do not "lock" the pipeline .
Naturally, the more complicated the logic of the loops and the more possible exit points exist, the harder it is for the compiler to optimize the loop in this way. This meant that the for
were traditionally more rigid than the while
, in order to take advantage of this advantage; for example, you could not change the value of the condition within the block that was executed.
Actually, I can not tell you to what extent processors still need (and compilers using) ' loop unrolling and to what extent a code like yours is a problem for a modern compiler if it wants to do an optimization, but I would be surprised if it meant a significant difference.
Readability
If it is correct that the custom causes that, when you see a for
, you expect that the execution does not depend on anything that is not what you define in for
itself (and therefore, you expect it to iterate) on all the elements).
In your code it is not difficult to see the break , but in larger blocks it can be ignored.
TL / DR The problem with if
looks like a remnant of past times; but I would advise that, if you are going to use break
or exit "unexpectedly", use a while for readability.
1 This is called pipelining .
2 This is related to a recently discovered vulnerability.
3 Normally the jump of a loop will be executed many times, and only once will it not be executed.