Using SymPy in Julia to convert a string of an expression I noticed a performance difference of factor ~3500 between the implementation of a native Julia function fast_fct
and the SymPy function slow_fct
generated from a string. Is there a way to speed up the SymPy function or is there a different, faster way achieving the same?
Please confer How to lambdify a list of strings with SymPy in Julia? for the function string_to_function
.
Minimal Working Example:
using SymPy
function string_to_function(fct_string)
expression = SymPy.sympify.(fct_string)
variables = free_symbols(expression)
function(args...)
subs.(expression, (variables .=> args)...)
end
end
function fast_fct(x, y, z)
return x + y + z
end
slow_fct = string_to_function("x + y + z")
Benchmarking
N = 100000
@time for i in 0:N
x, y, z = rand(3)
fast_fct(x, y, z)
end
@time for i in 0:N
x, y, z = rand(3)
slow_fct(x, y, z)
end
with the approximate results
>>> 0.014453 seconds (398.98 k allocations: 16.769 MiB, 40.48% gc time)
>>> 31.364378 seconds (13.04 M allocations: 377.752 MiB, 0.64% gc time, 0.41% compilation time)