Why use Atom?

tehaisperlis

Hazmi Irfan

Posted on November 27, 2020

Why use Atom?

Atom is describe as Constants whose values are their own name.

One of the use of Atom is that it allows you to pattern match.
For example you can pattern match the result:

case result do 
  {:ok, user} -> 
    #handle success
  {:error, changeset} -> 
    #handle error
end

Enter fullscreen mode Exit fullscreen mode

The code below is okay but when I first tried it, it looks no different to a constant string.

For example, we can change the code to look like this

case result do 
  {"ok", user} -> 
    #handle success
  {"error", changeset} -> 
    #handle error
end
Enter fullscreen mode Exit fullscreen mode

Instead of pattern matching an Atom, we pattern match a String instead.

The downside of this is that if we want to change ok to okay in the future, we need to change it everywhere. However, this is the same problem if we were to use an Atom.

So why should we use an Atom? Well, after some digging, I found out that Atom value are mapped at runtime. Basically Atom is a global value.

Why is this important? Lets take a look a the previous code

case result do 
  {"ok", user} -> 
    #handle success
  {"error", changeset} -> 
    #handle error
end
Enter fullscreen mode Exit fullscreen mode

If you see the code above, if we were to pattern match using String, Elixir would need to compare the character 1 by 1. This can obviously become cumbersome.

If we were to use an Atom instead, Elixir can just compare the pointer/address . We don't have to compare the value 1 by 1 because by default an Atom value is the same. This makes pattern matching much faster.

Also, the syntax is much nicer :D

馃挅 馃挭 馃檯 馃毄
tehaisperlis
Hazmi Irfan

Posted on November 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related