Today I Learned

Compiled patterns

Using compiled pattern in functions that accept it as a parameter, ex.: String.split/3 can be beneficial to the performance.

Compiled pattern cannot be stored in a module attribute as the pattern is generated at runtime.

Snippet

space = :binary.compile_pattern(" ")
phrases = Enum.map(1..100_000, fn _ -> "x y" end)

Benchee.run(
  %{
    "compiled pattern" => fn ->
      Enum.map(phrases, &String.split(&1, space))
    end,
    "pattern" => fn ->
      Enum.map(phrases, &String.split(&1, " "))
    end
  }
)

Results

Name                       ips        average  deviation         median         99th %
compiled pattern         29.33       34.10 ms     ±4.32%       33.58 ms       41.01 ms
pattern                  21.73       46.01 ms     ±7.18%       45.14 ms       55.32 ms

Comparison:
compiled pattern         29.33
pattern                  21.73 - 1.35x slower +11.92 ms

Did you find the article interesting and helpful? Take a look at our Elixir page to find out more!

➡️ Hello! We are Appunite

#language #programming #framework