0
$\begingroup$

It appears to me that loop in mathematica is very slow (compared with matlab). Since many people still use mathematica to finish their work, there must be some techniques to bypass this problem.

Could you share your techniques of avoiding loop in mathematica with beginners like me?

$\endgroup$
  • 2
    $\begingroup$ Functional Programming beats loops every time, and is parallelizable. $\endgroup$ – Roman Jul 5 '19 at 14:39
  • 2
    $\begingroup$ "It appears to me that loop in mathematica is very slow" - please give some explanation to back up this statement. $\endgroup$ – Jason B. Jul 5 '19 at 14:59
  • 1
    $\begingroup$ Procedural loops are slow in all interpreted languages unless they are JIT-compiled. $\endgroup$ – Henrik Schumacher Jul 5 '19 at 15:07
  • 1
    $\begingroup$ For number crunching, vectorization and (reformulating as many things as possible into linear algebra (matrices, and SparseArray)) works best. Followed by Compile with options CompilationTarget -> "C", RuntimeAttributes -> Listable, Parallelization -> True. $\endgroup$ – Henrik Schumacher Jul 5 '19 at 15:09
  • 2
    $\begingroup$ Code like j=0; For[i=0, i<10^7, i++, j++];//AbsoluteTiming is indeed about 400 times slower than the same written in C. But as @HenrikSchumacher points out, this is true in every interpreted language. It also becomes irrelevant as soon as the loop body does any significant work, i.e. whenever the loop infrastructure overhead becomes negligible compared to the loop's "payload". When the loop body is very simple (as in the given example) there is usually a faster way of operating: vectorization, linear algebra, analytic solution, etc. $\endgroup$ – Roman Jul 5 '19 at 15:17