Table / Do
Both Table
and Do
are only barely functional programming, still generally used procedurally, but they are simple, much more efficient alternatives to For
and While
loops. All they do is loop over a list or range, with optional localized loop variables:
Compare:
For[ i = 1, i< 10^6, i++, PrimeQ@i]//
AbsoluteTiming//First
(*Out:*)
0.830501`
and
Do[ PrimeQ@i,{i,10^6}]//
AbsoluteTiming//First
(*Out:*)
0.31723`
It’s over 2x faster to use Do
here and the result is exactly the same. Moreover, as shown before, Table
will automatically accumulate the results of each step, with huge efficiency gains over the equivalent procedural construct:
results={};
For[ i = 1, i< 2.5*10^4, i++,AppendTo[results, PrimeQ@i]]//
AbsoluteTiming//First
(*Out:*)
3.008666`
Table[PrimeQ@i,{i,2.5*10^4}]//
AbsoluteTiming//First
(*Out:*)
0.008375`