Note that there are some explanatory texts on larger screens.

plurals
  1. POExecute Code Segment only if Loop reaches its last cycle (End of Loop)
    text
    copied!<p>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)?</p> <p>The question seems banal, the answer obvious, nevertheless I am insecure!</p> <p>Answer from efficiency/theory professionals very welcome!</p> <hr> <ol> <li><p><strong>Provided</strong>: "Some Code X" is always the same, only at different Code Segment Positions 1 and 2.</p></li> <li><p><strong>I assume</strong>: 2 will be executed with the same reliability as 1. Am I wrong?</p></li> <li><p><strong>I know:</strong> 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 <strong>efficiency difference</strong> is <strong>if-condition queried $limit times</strong>.</p></li> </ol> <p>Hence I conclude: To prefer using Code Segment 2 rather than Code Segment 1, unless my assumption is wrong!</p> <hr> <pre><code>for ($i = 0; $i &lt;= $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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload