Which is more efficient for iterative programs: while loops or terminating with an if statement and break command?
1 view (last 30 days)
Show older comments
Just as the title of the question says, which method is more efficient, both in terms of memory and CPU usage. I'm sure this is common question, but I've not been able to find the right search terms to get an answer..
Sample code is provided below:
%while loop example
i=1;
criteria(i)=0;
while criteria(i)==0 %set an end criteria
for i=someArray
[output(i),criteria(i)]=fcn(input(i));%when fcn meets threshold, it outputs criteria=1
end
end
%if statement with break
for i=someArray
[output(i),criteria]=fcn(input(i));%same function as above
if criteria(i)==1
break
end
end
Also, out of curiosity, if there is a difference in efficiency, why is that the case?
Thanks in advance!
4 Comments
Rik
on 8 Dec 2020
Especially for 10^6 iterations it will be very important to use pre-allocation:
timeit(@foo)
timeit(@bar)
function foo
x=[];
for n=1:10^6
x(n)=rand;
end
end
function bar
x=zeros(1,10^6);
for n=1:10^6
x(n)=rand;
end
end
while with break might add or shave off a few parts in a thousand, pre-allocation shaves off two-thirds. Pre-allocation doens't have to reduces code readability for beginners, especially if you write a comment.
Answers (1)
Paul Hoffrichter
on 8 Dec 2020
Edited: Paul Hoffrichter
on 8 Dec 2020
for the "%if statement with break":
Suppose someArray has a million elements in it. If, in the 10th iteration, criteria(i)==1, then you have broken out of the loop.
In the same scenario with the "%while loop example" double loop case, the inner for-loop continues for all million elements, which takes a little longer than the "%if statement with break".
Normally, you try to estimate the size of the arrays. But since you did not, then, on average, in the above scenario, you will have created only 10 elements of output and criteria, whereas in the while loop, you always create a million elements - a little larger memory required.
In your example, breaking out of the loop is reduces memory and cpu usage on average.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!