Speed Demonstration

Mathematica provides many different ways of doing the same thing. However, some implementations are much faster than others! Consider the following examples.

Listing squares

Suppose we want to make a list of the squares of the fist n positive integers: {1, 4, 9, 16, ..., (n^2)}. We could do this using a Module containing a Do loop:

squares1[n_]:=Module[{list={}},
Do[ AppendTo[list,i^2],n ];
list
]

Alternately, we could map a range to the squared function (implemented as a pure function):

squares2[n_]:=(#^2&)/@Range[n]

Let’s see how the runtimes compare:

Timing[squares1[100000]][[1]]

Timing[squares2[100000]][[1]]

Operations on decimals and fractions

As we have already seen, operating on decimals is much faster than operating on fractions. Here, we will evaluate a function 10,000 times using decimal inputs, then we will repeat using fraction inputs.

f[x_]:=(x+1)^50*(x+2)^72

Timing[f/@Range[0,1,0.0001];]

Timing[f/@Range[0,1,1/10000];]