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" *)
With[{a = Quotient[1000000 (1000000 - 1), 2]}, f[x_] := a (x (1 + x (1 + x)))];
;) $\endgroup$