Remembering values for reuse

I wish to clarify an aspect which I find interesting and potentially useful.

If I define a function in the following manner:

f[x_] := f[x] = (*What the function does*)

and then I evaluate the function at “a”, does this mean that later it will treat f(a) as a constant?

If so, theoretically it shouldn’t increase my computation time, if let’s say I implement a For loop where for different ranges I use f(a), f(b), f(c),.. , compared to when I use instead upfront defined variables (A=f(a), B=f(b), C=f(c),..), right?

Or this feature is only useful for recursions?

Hello Sandu,

This is a very useful feature---and not just for recursion.

You can change the value the f later. For example

func[x_] := func[x] = Date[]
func[now]
Pause[3]
func[now]

func[now] = Date[]
Pause[1]
func[now]

I find this method useful to build up indexed lists when I don’t know the size of a list a priori. For a simple (not particularly useful) example which illustrates trading memory for speed.

n = 300; m = 500; icount = 0;
SeedRandom[1]

image = Table[pixel[++icount] = RandomReal[]; 
  valueLocation[pixel[icount]] = {i, j}; 
  pixel[icount], {i, 1, n}, {j, 1, m}]

pixel[12]

theTargetPix = image[[137, 314]]

posTime = Timing[Do[Position[image, theTargetPix], {100}]]
idxTime = Timing[Do[valueLocation[theTargetPix], {100}]]
First[posTime]/First[idxTime]  (*I get around 10^4*)

WCC