How do I make my Mathematica programs run faster?

Use the newest version

New versions of Mathematica often include major speed gains and new built in functions that can speed up your calculations significantly.
For example, compare Version 4 against version 3 for calculating autocorrelations.

a = Table[2*Random[Integer] - 1, {10230}] ;

In version 3, this calculation takes 150 seconds.

Timing[Table[a . RotateLeft[a, i], {i, 0, 10229}];]

Version 4 is about 5 times faster right out of the box.

Timing[Table[a . RotateLeft[a, i], {i, 0, 10229}];]

But Version 4 also has a new built-in function for calculating list correlations. Using this, the calculation is over 340 times faster than before.

Timing[ListCorrelate[a, a, 1];]

Some other speed improvements in Mathematica 4 include:

({{Calculation, Mathematica 3, Mathematica 4, Performance Ratio}, {Sin[m], 2.433 Second, 0.13 Second, 18.7 : 1}, {(((m + 1))^100), 4.426 Second, 0.311 Second, 14.23 : 1}, {Min[m], 4.487 Second, 0.02 Second, 224 : 1}})

Use built-in functions

Built in Mathematica functions are usually far more efficient and faster than user written code that duplicated their functionality. Part of the reason for this is that many of them use proprietary algorithms, are highly optimized and many are implemented in C code. Looking if a function you are trying to implement is already built into Mathematica is time well spent. Also keep in mind that Mathematica not only contains thousands of mathematica functions, but also a large number of utility functions like Sort.

For example, here is a pretty nifty way to calculate an autocorrelation

Table[a . RotateLeft[a, i], {i, 0, Length[a]}]

This is pretty much as good and terse top level code for doing this calculation as possible. Or, at least it's a lot better than

result = {};
Do[AppendTo[result, a . RotateLeft[a, i]], {i, 0, 
        Length[a]}]

And it looks reasonably fast for small sets of numbers.

a = Table[Random[], {1000}];

Timing[Table[a . RotateLeft[a, i], {i, 0, Length[a]}];]

But let's try this on a rather large set of data.

a = Table[Random[], {100000}];

Timing[Table[a . RotateLeft[a, i], {i, 0, Length[a]}];]

The built in function ListCorrelate cuts the time needed by a factor of over 2350.

Timing[ListCorrelate[a, a, 1];]

Use machine precision numbers

One of the most important things to notice when doing numerical calculations is that Mathematica uses fundamentally different evaluation mechanisms for floating point and exact numerical quantities like integers and fractions. And usually, the floating point calculations are hugely faster than exact arithmetic, so use them wherever appropriate.
 Take a look at the following example:

a = Table[Random[Integer], {32}, {32}];

a // MatrixForm

inttime = Timing[Eigenvalues[a];]

Mathematica takes about 2.36 seconds to calculate the eigenvalues of this matrix. Actually, this is pretty fast. But by simply changing the entries to floating points.

a = N[a];

The calculations of the eigenvalues becomes pretty much instantaneous.

floattime = Timing[Eigenvalues[a];]

Avoid procedural programming

For users coming from other languages like C, FORTRAN or Matlab, using procedural constructs is tempting. But procedual programming gives, with very few exceptions, extremely poor performance compared with functional programming.

Timing[t = 0.37; Do[t = 4  t (1 - t), {100000}]; t]

Timing[Nest[(4 # (1 -  #)) &, 0.37, 100000]]

Operate on lists as a whole, not on individual parts.

Mathematica is able to operate on whole lists at once, or using the new PackedArray technology, even on lists in an internal compressed form. This is much faster than stepping through lists calculating single elements. Also, keep in mind list manipulation functions like Partition.
This effect is already quite significant for simple operations like taking the sine of all elements in a list.

Timing[Table[Sin[x], {x, 0,  π, (π/10000.) }];]

Timing[Sin[Range[0, π, (π/10000.) ]];]

For a more realistic example, lets say we have two vectors of x and y values which we want to combine into a list of {x,y} pairs.

a = Table[Random[], {10000}];
b = Table[Random[], {10000}];

A pretty straightforward approach would be constructing a new table.

Timing[newtable = 
          Table[{a[[i]], b[[i]]}, {i, 1, Length[a]}];]

newtable[[1]]

Combining the lists, transposing and partitioning them gives the same result, but is infinitely faster.

Timing[newtablefast = Transpose[{a, b}];]

newtablefast[[1]]

Use Compile

In many numerical computations, one of the easiest ways of getting more performance is using the built in compiler. Often, doing this is as easy as wrapping Compile[args, ...] around your function.

f[x_, n_] := 
        Module[{t}, t = x; Do[t = 4 t (1 - t), {n}]; t];

Timing[f[0.37, 100000]]

fc = 
        Compile[{x, {n, _Integer}}, 
          Module[{t}, t = x; Do[t = 4 t (1 - t), {n}]; 
            t]];

Timing[fc[0.37, 100000]]

For more information about compile, see the relevant sections of the Mathematica book or the Mathematica bookstore

Use the Parallel Computing Toolkit

If you have to run large scale calculations, the Parallel Computing Toolkit might be just the solution you are looking for.
The Parallel Computing Toolkit brings parallel computation to anybody having access to more then one computer on a network or a multi-processor computer. It implements many parallel programming primitives, and includes high level commands for parallel execution of operations such as animation, plotting and matrix manipulation. Also supported are many popular new programming approaches such as parallel Monte Carlo simulation, visualization, searching and optimization. The implementations for all  high level commands in the Parallel Computing Toolkit are provided in Mathematica source form, and serve as templates for building additional parallel programs.

Use MathCode

MathCode C++is an application package forMathematica that generates optimized C++ code for numerical computations. Some of its features and advantages are:

Compiled code can easily be called from within Mathematica.

Optionally, stand-alone code can be generated (i.e. code that can be executed independent of Mathematica).

Increase in performance up to 5000 times for some computations.

External libraries of C, C++, and Fortran77 code can easily be connected and called from within Mathematica.

Extended functionality for extraction of parts of matrices.

To learn more about MathCode C++, check out our product pages