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

**URL:** <https://discourse.julialang.org/t/how-to-convert-symbolics-jl-expressions-to-functions-while-keeping-speed/98111>\
**Category:** General Usage\
**Tags:** question, functions, symbolics\
**Created:** [April 30, 2023, 3:39am UTC](https://discourse.julialang.org/t/how-to-convert-symbolics-jl-expressions-to-functions-while-keeping-speed/98111 "2023-04-30T03:39:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tony\_Zhang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tony_zhang/32/31921_2.png) [@Tony\_Zhang](https://discourse.julialang.org/u/Tony_Zhang)\
**Post date:** [April 30, 2023, 3:39am UTC](https://discourse.julialang.org/t/how-to-convert-symbolics-jl-expressions-to-functions-while-keeping-speed/98111/1 "2023-04-30T03:39:35Z")

</div>

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:

```julia
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)

```

---

<div class="post-metadata">

**Author:** ![Elrod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/elrod/32/22461_2.png) [@Elrod](https://discourse.julialang.org/u/Elrod)\
**Post date:** [April 30, 2023, 3:55am UTC](https://discourse.julialang.org/t/how-to-convert-symbolics-jl-expressions-to-functions-while-keeping-speed/98111/2 "2023-04-30T03:55:47Z")

</div>

```julia
const fexpr = build_function(expr, x, y, expression = Val{false})

```

`f_defn` is `const`, while `fexpr` is not.

---

<div class="post-metadata">

**Author:** ![Tony\_Zhang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tony_zhang/32/31921_2.png) [@Tony\_Zhang](https://discourse.julialang.org/u/Tony_Zhang)\
**Post date:** [April 30, 2023, 5:16am UTC](https://discourse.julialang.org/t/how-to-convert-symbolics-jl-expressions-to-functions-while-keeping-speed/98111/3 "2023-04-30T05:16:34Z")

</div>

Thank you!
