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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With