CharlesO

CharlesO

Does placing the most likely-matched function heads first offer any benefit?

Say we have several function heads or case do patterns to match on.

Will placing “common case” or “most likely” headers first offer any benefits?

I’m seeing timing improvements when I re-order case do match patterns in ELIXIR, putting the most common pattern first.

I had expected the VM to optimize this away, and the order shouldn’t matter.

Example:

  for {s, i} <- li do
    case :binary.split(s, spliter, [:global]) do
      [_, tag, val, _, _] -> 
        # this pattern occurs over 9/10 times.
        # in files with over 100000 rows matching this pattern
        # reduced processing time
        {:tv, i, tag, val}

      [_, "data", _] ->
        Process.put(:data_tag, true)
        {:tb, i, "data"}

      [_, "/data", _] ->
        Process.put(:data_tag, false)
        {:te, i, "data"}

      [_, "/" <> tag, _] ->
        if Process.get(:data_tag) do
          {nil, i}
        else
          {:te, i, tag}
        end

      [_, "?xml" <> _, _] ->
        {nil, i}

      [_, "!--" <> _, _] ->
        {nil, i}

      [_, "return" <> _, _] ->
        {nil, i}

      [_, tag, _] ->
        if Process.get(:data_tag) do
          {:tv, i, tag, ""}
        else
          {:tb, i, tag}
        end

      _ ->
        {nil, i}
    end
  end

Most Liked

rvirding

rvirding

Creator of Erlang

The Erlang compiler is quite smart when compiling patterns but there are some things which are extremely difficult to optimise. So it can be really smart with atoms, integers, tuples and lists. However strings, and binaries which is how they are implemented, are much more difficult; in many cases it can’t do better then testing them sequentially which is why you can get some improvement by reordering them. This is a case where lists strings can be more efficient. :grinning:

So in your example it can group all the clauses and only do the list checking and extracting only once it still needs to test the strings sequentially.

Note that while the pattern matching compiler may choose to reorder clauses and checking it will semantically always behave as if it is done sequentially.

tty

tty

In Erlang function heads and case are pattern match from top down. I expect Elixir would be similar. In general I prefer ordering in the most readable manner, especially for the poor sod (usually me) who has to support the code.

Qqwy

Qqwy

TypeCheck Core Team

Thinking too much about this is very likely a case of premature optimization: Only if you have an actual implementation that is too slow in a certain regard, and you have benchmarks that measure this, does it make sense to optimize in such a way.

Until you ever reach such a situation, readability is more important than hypothetical speed.


That said, I’m fairly certain (based on earlier papers on the implementations of pattern-matching I read) that Erlang is able to do at least a binary-search if the patterns are restrictive enough. (And patterns/guards that occur in multiple patterns are also probably only executed once). In some limited cases it might even be possible to perform an immediate jump to the correct implementation (such as when all patterns are different consecutive integer values).

In other cases, indeed, the first pattern is matched first, and then we continue on to the next.

Where Next?

Popular in Questions Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
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
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
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54120 245
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement