Where is the most efficient position for a code block, which shall only execute, if a loop has reached its end, without having previously been aborted (via break or return)?
The question seems banal, the answer obvious, nevertheless I am insecure!
Answer from efficiency/theory professionals very welcome!
Provided: "Some Code X" is always the same, only at different Code Segment Positions 1 and 2.
I assume: 2 will be executed with the same reliability as 1. Am I wrong?
I know: 2 is obviously more efficient, as it is only called once after the loop ran $limit times, compared to 1, whose enclosing if-condition is called $limit times, and if once true, the code itself is called. Thus the efficiency difference is if-condition queried $limit times.
Hence I conclude: To prefer using Code Segment 2 rather than Code Segment 1, unless my assumption is wrong!
for ($i = 0; $i <= $limit; $i++) {
// Some Code A [...]
// Executed every iteration.
// If condition is met, abort the loop and return $result
if (condition) {
return $result;
}
// Code Segment 1, only executed in last iteration if no abortion happened previously. If-condition checked $limit times!
if ($i == $limit) {
// Some Code X [...]
return $result
}
}
// Code Segment 2, only executed if no abortion happened. At most executed only once!
// Some Code X [...]
return $result