开发者

Execute Code Segment only if Loop reaches its last cycle (End of Loop)

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!


  1. Pro开发者_StackOverflow社区vided: "Some Code X" is always the same, only at different Code Segment Positions 1 and 2.

  2. I assume: 2 will be executed with the same reliability as 1. Am I wrong?

  3. 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


Something like this?:

$aborted = false;
for ($i = 0; $i <= $limit; $i++) {
    // Code
    if ($condition) {
        // Code
        $aborted = true;
        break;
    } else {
        // Code
    }
}

if ($aborted) {
    // Code
} else {
    // Code
}

return $result;

If you're going through an array (or other iterable structure), use a foreach loop and put your "completed loop" code following it.


You have concluded correctly .. segment 2 is far more efficient than segment 1 .. for the reasons you have already stated.

I terms of complexity, in case of the for loop u have O(n) ( where n = $limit ) and incase of segment 2 it is a constant O(1) .. so yes segment 2 is the way to go.


if you are using return when you stop a loop, then the second block after the loop will always be executed, as return stops the entire function.

if you are using break. something like the if($i==$limit) statement you have is fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜