Which is more efficient for iterative programs: while loops or terminating with an if statement and break command?
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
Rik
2020-12-8
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.
回答(1 个)
Paul Hoffrichter
2020-12-8
编辑:Paul Hoffrichter
2020-12-8
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!