Performance
Prerequisites: Scoping and evaluation control
Wolfram Language code can be very fast or very slow depending on style.
Measure first: AbsoluteTiming[expr] returns {seconds, result}, and
RepeatedTiming averages several runs.
Vectorize
Listable built-ins run in optimized compiled code. Loops that update variables run one step at a time in the interpreter:
AbsoluteTiming[s = 0; Do[s += i^2, {i, 10^6}]; s]
AbsoluteTiming[Total[Range[10^6]^2]]
Both return {seconds, 333333833333500000} — the same exact answer — but
the vectorized version is typically tens to hundreds of times faster. The
exact timings depend on your machine.
Packed arrays
Lists of machine numbers of one type are stored as packed arrays — contiguous memory, like a C array. Mixing types unpacks them:
Developer`PackedArrayQ[Range[10]]
Developer`PackedArrayQ[RandomReal[1, 1000]]
Developer`PackedArrayQ[{1, 2.5, "a"}]
True
True
False
Keep numeric data packed: avoid mixing integers, reals, and symbols in
one list, and prefer functions that return whole arrays (Range,
Table, RandomReal, arithmetic) over building lists element by
element.
Memoization
A definition that stores its own results turns exponential recursion into linear:
fib[0] = 0;
fib[1] = 1;
fib[n_Integer?Positive] := fib[n] = fib[n - 1] + fib[n - 2]
fib[100]
354224848179261915075
fib[n] = ... inside the definition saves each value as a new, specific
rule the first time it's computed.
Compiling
Compile turns numeric code into fast bytecode (or C, with
CompilationTarget -> "C"):
cf = Compile[{{x, _Real}}, x^2 + Sin[x]];
cf[1.0]
1.84147
The newer Wolfram Compiler uses FunctionCompile with typed
arguments and generates native machine code:
fc = FunctionCompile[Function[Typed[n, "MachineInteger"], n^2 + 1]];
fc[5]
26
Compile only after vectorizing: many tasks are already fast with built-in listable functions.
Parallel computing
(* illustrative *)
LaunchKernels[];
ParallelMap[PrimeQ[2^# - 1] &, Range[2000, 3000]]
ParallelMap, ParallelTable, and ParallelDo spread independent work
across subkernels (CPU cores). The number of kernels you may run depends
on your license. Parallelism helps when each item takes real time;
for tiny tasks the communication cost dominates.
Checklist
- Measure with
AbsoluteTiming. - Replace loops with listable operations,
Map,Table, and built-ins. - Keep numeric data packed and approximate (
N) when exact results aren't needed. - Memoize repeated expensive calls.
- Compile tight numeric loops that can't be vectorized.
- Parallelize independent, expensive tasks.