Here are some examples of the type of for-loops I've seen from those coming to Mathematica from imperative programming languages like C/Java, where for-loops dominate. I'll present non-for-loop equivalents, in some cases with timings, which will be seen to be an significant difference.
Iterate a command f[]
(here f
is a no-op, so the timing reflects the overheads of For
and Do
):
ClearAll[f, i];
For[i = 1, i <= 10^6, i++, f[i]]; // AbsoluteTiming (* i is a global variable *)
i
Clear[i]
Do[f[i], {i, 10^6}]; // AbsoluteTiming (* i is a local variable *)
i
(* Out[]=
{1.01164, Null}
1000001
{0.226265, Null}
i
*)
Note that i
is not localized in For
. The user has to localize i
explicitly to get an equivalent behavior of Do
:
Block[{i}, For[i = 1, i <= 10^6, i++, f[i]]] (* user-localized i *)
Compute some data:
For[i = 1, i <= 10, i++, Print[Sin[0.1 i]]];
data = Table[Sin[0.1 i], {i, 10}];
data // TableForm
Note that the data is not stored in the For
loop above, which is not at all a smart way to compute data, but I've seen it done often. Below is the typical way one would compute data. For the for-loop way, you first declare/allocate an array, and then fill it with values. With Table[]
, it's all handled for you and very efficiently.
(data = ConstantArray[0., 10^6]; (* pre-allocate array *)
For[i = 1, i <= 10^6, i++, data[[i]] = Sin[0.1 i]];) // AbsoluteTiming
data = Table[Sin[0.1 i], {i, 10^6}]; // AbsoluteTiming
(* Out[]=
{2.61934, Null}
{0.072018, Null}
*)
The time difference is staggering.
One reason For
is less efficient is that it is a very general scheme. Any expression may be an iterator (3rd argument). The most common uses, however, are the ones shown (to iterate over a range of integers or to step through a list). Do
and Table
are optimized for these tasks. Personally, I've always felt For
was mainly a convenience for translating C code (etc.) to Mathematica. Its greater generality does open the possibility that there might be some computations that are more naturally expressed with For
. Maybe.