Search code examples
performancecoding-styleerlangpattern-matchingrecord

Which is more efficient in Erlang: match on two different lines, or match in tuple?


Which of these two is more efficient in Erlang? This:

ValueA = MyRecord#my_record.value_a,
ValueB = MyRecord#my_record.value_b.

Or this:

{ValueA, ValueB} = {MyRecord#my_record.value_a, MyRecord#my_record.value_b}.

?

I ask because the latter sometimes brings me to need multiple lines to fit in the 80 character line length limit I like to keep, and I tend to prefer to avoid doing stuff like this:

{ValueA, ValueB} = { MyRecord#my_record.value_a
                   , MyRecord#my_record.value_b }.

Solution

  • They generate exactly the same code! If you want less code try using:

    #my_record{value_a=ValueA,value_b=ValueB} = MyRecord
    

    which also generates the same code. Generally, if you can, use pattern matching. It is never worse, usually better. In this case they all do the minimum amount of work which is necessary.

    In general write the code which is clearest and looks the best and only worry about these types of optimisation when you know that there is a speed problem with this code.