How to convert Symbolics.jl expressions to functions while keeping speed?

Hello!

I’m using Symbolics.jl to perform some symbolic computations and then convert the resulting expressions to functions for further use. However, when I use build_function to generate functions, the speed is only a quarter of that when I directly define the function. How can I optimize this?

Thank you all in advance!

Following is an example:

using Symbolics
using BenchmarkTools

@variables x y
f(x,y) = x^2 + sin(x+y)
D = Differential(x)
expr = expand_derivatives(D(f(x,y)))  # output: 2x + cos(x + y)

# generate the function from the expression
f_expr = build_function(expr, x, y, expression = Val{false})
# define the function directly
f_defn(x, y) = 2x + cos(x + y)

# benchmarks
@btime for x in rand(100), y in rand(100)
	f_expr(x, y)
end
# output: 239.600 μs (30101 allocations: 557.12 KiB)

@btime for x in rand(100), y in rand(100)
	f_defn(x, y)
end
# output: 60.300 μs (101 allocations: 88.38 KiB)
const fexpr = build_function(expr, x, y, expression = Val{false})

f_defn is const, while fexpr is not.

4 Likes

Thank you!