I have a situation where I’d like to build some functions based on different inputs - using a callable function seems really clear to me, and has the functionality I want. I’d rather not use
eval and other metaprogramming stuff because it seems way more complicated, but it seems like functors have a huge performance penalty.
It’s also possible I’m missing something critical and obvious, but this is my first foray into doing anything like this. Here’s a super simplified example:
julia> function makef(p1, p2, p3) eval(Meta.parse("f(x) = $p1*x^2 + $p2*x + $p3")) end makef (generic function with 1 method) julia> makef(3, 2, 1) f (generic function with 1 method) julia> struct Polynomial p1 p2 p3 end julia> function (p::Polynomial)(x) p.p1*x^2 + p.p2*x + p.p3 end julia> g = Polynomial(3,2,1) Polynomial(3, 2, 1) julia> using BenchmarkTools [ Info: Precompiling BenchmarkTools [6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf] julia> @btime f(2) 0.030 ns (0 allocations: 0 bytes) 17 julia> @btime g(2) 55.050 ns (0 allocations: 0 bytes) 17
Based on other discussions around stuff like this, I’m guessing something is being compiled away in
f but not in
g, but I’m not clear on why that would be, or if there’s a way to help
g along a bit.