hansonkd

hansonkd

Dynamic function generation at runtime with Code.eval_... very slow

Hi.

I am making a library for user submitted templates (so users can customize email content). I have a parser which parses the template to an AST, and now I am implementing evaluating the template. My first pass was to interpret the template, going over the AST every time it renders, then my second pass was to build an anonymous function from the AST (so it is recursive anonymous functions for the different branches of the AST), now on my 3rd pass, I am building up an Elixir AST which in turn evaluates to a function.

My code uses quoted expressions, but it is easier to show the problem using strings:

with this string:

{compiledB, _} =
    Code.eval_string("""
        fn vars ->
          %{"my_var" => userVar_0} = vars
          [["(", to_string(userVar_0), ":", to_string(userVar_0), ")"]]
        end
        """)
Benchmark.measure(fn ->
        %{"my_var" => 20}
        |> compiledB.()
        |> IO.iodata_to_binary
end)

Where Benchmark.measure calls the function 1000 times takes 0.025493 seconds, which is slower then interpreting it.

If I change it to do this:

Code.compile_string("""
    defmodule A do
        def render(vars) do
          %{"my_var" => userVar_0} = vars
          [["(", to_string(userVar_0), ":", to_string(userVar_0), ")"]]
        end
    end
    """)
Benchmark.measure(fn ->
        %{"my_var" => 20}
        |> A.render()
        |> IO.iodata_to_binary
end)

Running this 1000 times takes 4.37e-4 seconds

I like eval_string, since it returns an anonymous function right away and the function is isolated from the rest of the execution environment. Using the compile option, I can’t compile it into an anonymous function, only a module, which then gets put into the Elixir environment so I would have to make sure Module names are unique (but not too unique so I don’t run out of atoms). I would also need to purge manually any templates that aren’t used anymore, whereas with eval_string, I assume the garbage collector would handle cleaning them up automatically.

Why is eval_string several orders of magnitude slower? Is using compile_string and then keeping track of module names and purging them when no longer needed the way to go?

Thanks!

First Post!

dom

dom

Are you running these benchmarks directly in IEx?

Most Liked

michalmuskala

michalmuskala

Only code inside modules is compiled, code outside modules is always interpreted through erl_eval. So even when you define the fun inside Code.eval_string you’re not compiling the function - what you receive is a reference to a function that will be interpreted when executed. That’s why threre’s not much performance difference and why code inside a module is so much faster.

josevalim

josevalim

Creator of Elixir

The purpose of the program definitely matters, because there may be simpler solutions available.

When you are evaluating code at runtime, there are at a minimum 4 or 5 compiler passes involved, to build something that is then evaluated (i.e. invoked by hand and not compiled). In your case, it is not clear why you need to use eval in the first place. Couldn’t you return the function?

compiledB =  fn vars ->
  %{"my_var" => userVar_0} = vars
  [["(", to_string(userVar_0), ":", to_string(userVar_0), ")"]]
end
hansonkd

hansonkd

Yes, you are probably right that interpreted is probably enough since IO to send the email will most likely be the limiting factor, performance wise.

Just incase anybody reads this in the future, my results on a small template with nested loops.(“compiledFully” uses Code.compile outlined above, “semi-compiled” is traversing the AST and building nested anon functions).

Compiling once then calling render (compile is outside loop)

Name                    ips        average  deviation         median         99th %
compiledFully       32.78 M      0.0305 μs    ±23.34%      0.0290 μs      0.0580 μs
semi-compiled      0.0337 M       29.71 μs    ±33.99%          27 μs          79 μs

Comparison: 
compiledFully       32.78 M
semi-compiled      0.0337 M - 973.78x slower

Compiling every render (compile is inside loop)

Name                    ips        average  deviation         median         99th %
semi-compiled        9.83 K       0.102 ms   ±342.27%      0.0920 ms       0.180 ms
compiledFully       0.105 K        9.50 ms     ±3.93%        9.49 ms       10.42 ms

Comparison: 
semi-compiled        9.83 K
compiledFully       0.105 K - 93.37x slower

So if you expect to use the compiled template more then 10-50x, it is worth it to compile it to Elixir.

Where Next?

Popular in Questions Top

ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

We're in Beta

About us Mission Statement