Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance implications when using "_var" over "_" in Elixir?

Tags:

elixir

There's a general rule to name any unused variables with an _ in Elixir. Doing so stops anything being bound to that variable.

However I have noticed a widely used pattern of prefixing with an underscore to denote an ignored argument, in the form of _tail (with the intention being to provide a hint as to what the variable would be).

This is encouraged by the language via a warning in the shell if you try to then access _tail:

warning: the underscored variable "_tail" is used after being set. A leading underscore indicates that the value of the variable should be ignored. If this is intended please rename the variable to remove the underscore

But here's the catch; _tail has the variable bound to it, whereas when using just _ it does not.

Does this mean that there's a performance penalty when naming ignored variables with anything other than an _? Or does Elixir still bind _ behind the scenes, and just error on any attempt to access?

Edit: It looks like the Erlang compiler specifically optimizes this case to treat _* as _ and thus there is no overhead, source: http://erlang.org/doc/efficiency_guide/myths.html

like image 257
whitfin Avatar asked Dec 28 '15 03:12

whitfin


2 Answers

Given everyone already gave the disclaimer to not worry about this kind of performance behaviour, the answer is: if a variable is not used, the compiler will notice it and the compiled bytecode will simply ignore it, as if you used _. That's the same reason why if you do x = 1 and never x, you get a compiler warning.

like image 109
José Valim Avatar answered Dec 08 '22 13:12

José Valim


Indeed there's special behaviour in Erlang (and hence Elixir) for the _ variable. But unless you measured that this is a performance problem for your application, I wouldn’t worry too much about this. I imagine overhead of binding variables would be completely insignificant if you're doing anything interesting inside the function.

like image 25
michalmuskala Avatar answered Dec 08 '22 13:12

michalmuskala