PragTob
Blog Post: 10 Elixir gotchas
Elixir is a great language, but some behavior can be unintuitive, confusing and in the worst case lead to bugs. So, I took a look at 10 Elixir gotchas explaining why they exist and how to avoid them!
Most Liked
sasajuric
Another gotcha with module attributes is that each reference injects the value, which can increase disk & mem usage. For example:
defmodule Foo do
@x Enum.to_list(1..1_000_000)
def foo, do: @x
def bar, do: @x
end
Here we inject two identical large lists in the code, and the resulting file is 6 MB.
In contrast, the following code:
defmodule Foo do
def foo, do: x()
def bar, do: x()
defp x, do: unquote(Enum.to_list(1..1_000_000))
end
produces a 4 MB beam, because the list is injected into the compiled beam only once.
In addition, I consider the 2nd version more flexible, because the “constant” can be provided after the implementation, which I often find better than listing various constants at the top of the file.
It’s also worth mentioning that both versions produce constants, as in terms which are handled in a special way by the runtime. See here for details.
BartOtten
Great post.
One more: is_atom(nil) == true as nil is an atom. However, most people mean a defined atom and not ‘undefined’ nil.
dwark
I got caught off guard by:
[1, 2, 3] -- [1, 2, 3] -- [1, 2, 3]
[1, 2, 3]
After checking, the docs spell it out neatly once I starting looking for an explanation
(-- is right-associative).
Popular in Blog Posts
Elixir Blog Post: Live video streaming from iOS devices made simple with Elixir & Membrane Framework
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









