The runtime efficiency is the same.
Calrity/readability is a heavy reason.
But this
foreach[/balso have the great advantage that whatever you put between do and end foreach must be procedure.
This can prevent mistakes where the loop backtracks too early:
Code: Select all
xxx_nd(...),
... % A
thisCanFailSometimes()
... % B
fail.
You intended the loop to run all the code between
xxx_nd and
fail for each
xxx_nd result.
But
thisCalFailSometimes can fail sometimes
, and when it does the B code will not be run for
xxx_nd result.
If you rewrite it using
foreach then the compiler will give an error:
Code: Select all
foreach xxx_nd(...)do
... % A
thisCanFailSometimes() % compiler error thisCanFailSometimes can fail
... % B
end foreach.
If you actually intended the code to work like that you can rewrite it like this:
Code: Select all
foreach xxx_nd(...)do
... % A
if thisCanFailSometimes() then
... % B
end if
end foreach.
This code is slightly less efficient, but on the other hand it is very clear what the code does and that it is intended to do so.
You should notice that
foreach always succeeds, whereas a fail loop always fails. So the "surrounding" code will also have to look different.