# Optimizing repeated function calls

Easiest way to keep my library nice, is to naively call some functions many times with same parameters. Doing so prevents from zoo of (library-)global variables and complicated initialisation functions. I would expect Mathematica to optimise somehow functions calls with same parameters, but it does not appear to do that.

Fallowing example is ran on Mathematica 9:

rands = Array[Random[] &, {2500, 2500}];
Timing[Inverse[rands];]
Timing[Inverse[rands];]
Timing[Inverse[rands];]
Timing[Inverse[rands];]


Output:

{0.687500, Null}
{0.687500, Null}
{0.687500, Null}
{0.687500, Null}


Is there a way to make Mathematica optimise revaluation with same parameters? What kind of nice workaround would you recommend?

EDIT As I learned, the keyword I needed was memoization. I found this post very useful. Thanks!

• Search this site for Memoization – Dr. belisarius May 18 '14 at 15:01

You can create a function like this

myInverse[x_]:= myInverse[x]=Inverse[x]


I get:

In[8]:= rands = Array[Random[] &, {2500, 2500}];

In[9]:= Timing[Inverse[rands];]
Timing[Inverse[rands];]
Timing[Inverse[rands];]

Out[9]= {6.292720, Null}
Out[10]= {5.771016, Null}
Out[11]= {5.534804, Null}

In[12]:= Timing[myInverse[rands];]
Timing[myInverse[rands];]
Timing[myInverse[rands];]

Out[12]= {5.842785, Null}
Out[13]= {0.000015, Null}
Out[14]= {4.\[CenterDot]10^-6, Null}