My question is how to define automatically in advance (once I know the coeff array), my polynomial functions for n=0:nmax as in poly1 the most efficiently? (Because I need to call these functions a lot of time after)
Note that this is a terrible way to evaluate polynomials. Use @evalpoly(x, -8.111, -12.8858, 1.62521, 1), which basically expands to Horner’s rule.
X = [x^j for j in 0:n]
This is also a terrible way to evaluate polynomials, even given a coefficient array. Use Horner’s rule. (If you use the Polynomials.jl package to store polynomials, it will do this. Or just use evalpoly in Julia 1.4.)
You can use code generation to generate functions for given polynomials, but I would do this as a last resort. First, fix your code.
In fact, if you store the polynomial coefficients as tuples rather than arrays, the evalpoly function, which I believe was added in Julia 1.4, should be basically as fast as inlined code generation.
function poly1_correct(n::Int64, x)
if n == 0
elseif n == 1
elseif n == 2
elseif n == 3
return @evalpoly(x, -8.111,-12.8858,1.62521,1)
For the one with coeff I am not sur how to code that
for n in 1:3
@evalpoly x $(coeff[n]...)
it works fast 0.021 ns (0 allocations: 0 bytes)
but it does not work because it returns only g(3,x). Note that I could not get it working without the first @eval.
Maybe with Julia 1.4 it will work more smoothly?
Thanks for the tip. I agree that Horner’s rule is better:
function poly_3(n::Int64, x, coeff)
if n == 0
27.258 ns (1 allocation: 16 bytes)
34.941 ns (1 allocation: 16 bytes)
37.842 ns (1 allocation: 16 bytes)
37.923 ns (1 allocation: 16 bytes)
But it still does not match the timing of poly1 function defined at the top of the thread.
Is there a way to define these functions coefficients before usage?
It is not only for this problem but a more generic questions (I have polynomial product with fixed coefficients that I also want to pre-evaluate because I need to call them a lot of time).
You mentioned code generation I tried to look it up but I am not sure how to apply it here, any advices?
Thanks for the help.
You are not benchmarking correctly; you need to “interpolate” to avoid accessing the global variable c3. Unfortunately currently you need to do this as follows with the strange Ref syntax and the  indexing:
If you search the forums on the document about performance and global variables you will find descriptions of why accessing global variables has bad performance and how to test around it. A simple way to do it is:
@btime evalpoly(1.3, $c3)
However like @dpsanders said, if the time is less than a nano second the compiler is doing optimizations on you and you are not benchmarking the actual operation.