# Memoize a compiled function

Let f be some function, I know that i can memoize a function so that it does not compute again previously calculated values, I can also compile the function to speed up the calculations. But how can I memoize a compiled function ? Ideally I would want to do something like this

Clear[f]
f[x_] := Total[Table[i*x + i*x^2 + i*x^3, {i, 1000000}]];
f[12.] // RepeatedTiming (* timing for the non memoized non compile function*)
Clear[f]
f = Compile[{{x, _Real}}, Total[Table[i*x + i*x^2 + i*x^3, {i, 1000000}]]];
f[12.] // RepeatedTiming  (*timing for the non memoized compiled function,this ideally should be faster than the non compiled function  *)
f[-12.] // RepeatedTiming (*timing for the non memoized compiled function,this ideally should be faster than the non compiled function   *)
Clear[f]
f[x_] :=
f[x] = f[-x] =
Compile[{{x, _Real}},
Total[Table[
i*x + i*x^2 + i*x^3, {i,
1000000}]]]; (* This syntax is incorrect, what I am trying to say is f is a compiled function, and the result for x and -x are the same anfd should be stored*)
f[12.] // RepeatedTiming(*timing for the memoized compiled function,this ideally should be faster than the non compiled function*)
f[-12.] // RepeatedTiming(*timing for the memoized compiled function, this ideally should be "instantaneous" *)

• I'd propose With[{a = Quotient[1000000 (1000000 - 1), 2]}, f[x_] := a (x (1 + x (1 + x)))]; ;) May 31 at 2:23

You can use a separate CompiledFunction cf as a fallback when the argument does not appear in the DownValues of f.

cf = Compile[{{x, _Real}},
Sum[i (x + x^2 + x^3), {i, 1, 1000000}],
CompilationTarget -> "C"
];

ClearAll[f];
f[x_] := f[x] = cf[x];


I would not use f[x_] := f[x] = f[-x] = cf[x]; as the result is not independent of the sign of the argument.

• Not really addressing your question of memorizing compiled function but as an aside, note that if all you are doing is summing the table then you don't actually need apply Table and Total. Note that f[x]=(x + x^2 + x^3) 1000000 1000001 /2
– jmm
May 31 at 17:30
• Thank you @jmm and Henrik Schumacher, yes the example does not make sense I just wrote some random function ! May 31 at 20:25
• You‘re welcome. Jun 1 at 0:13