# Precomputing Function with ReplaceAll[]

I have a function f that is a combination of multiple other functions g_i, which themselves are combinations of other functions h_ij

f=Function[{x},g_1[x]+g_2[x]+...+g_n[x]]
g_i=Function[{x},h_i1[x]+h_i2[x]+...+h_im[x]]


If I evaluate f the evaluation takes about 20 seconds, however if I define F=f[x] then run F/.{x->0} the evaluation takes about 0.01 seconds.

Is it possible to "precompute" f so I don't need to use ReplaceAll to benefit from the speed boost?

Example Code

g = Table[With[{b = i},
Function[{x}, Values[Solve[a*b^x == I, a][[1, 1]] ] ] ],
{i, Table[RandomComplex[], 1000]}
];

f = Function[{x}, Total[Through[g[x] ] ] ];


When running f I get an evaluation time of ~0.08 seconds, but when running F=f[x]; F/.{x->4} the run time is ~0.004 seconds.

• Could you update your code so the other can replicate the issue. – ercegovac Oct 8 '17 at 20:07
• The actual code is about 1000 lines long, is there another way to give more info? – bicarlsen Oct 8 '17 at 20:09
• Can you provide a relatively simple example that illustrates the issue? – bbgodfrey Oct 8 '17 at 20:14
• Maybe, you are looking for f=Function[{x},Evaluate[g_1[x]+g_2[x]+...+g_n[x]]]? – Henrik Schumacher Oct 8 '17 at 20:18
• What you do is essentially solve the set of equations every time. As @HenrikSchumacher suggested, use Evaluate. – ercegovac Oct 8 '17 at 20:41

Using Evaluate around the functions in f did the trick, as suggested in the comments.
 f=Function[{x},Evaluate[g_1[x]+g_2[x]+...+g_n[x]]]