0

Between binary patterns & string concatenation, what is the fastest method to match strings?

Binary patterns

<<"test"::utf8, rest::bytes>> = "test string"

String concatenation

"test" <> rest = "test string"
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56

1 Answers1

4

Both the snippets compile to exactly the same Erlang code so they'll run at exactly the same speed. We can verify this using decompile-beam.

$ cat a.exs
defmodule A do
  def a do
    <<"test"::utf8, rest::bytes>> = "test string"
  end

  def b do
    "test" <> rest = "test string"
  end
end
$ elixirc a.exs
$ decompile-beam Elixir.A.beam
...

a() ->
    <<"test"/utf8, rest@1/binary>> = <<"test string">>.

b() -> <<"test", rest@1/binary>> = <<"test string">>.
Dogbert
  • 212,659
  • 41
  • 396
  • 397