Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending messages among erlang processes: Atoms vs Binaries

Are atoms copied from one process to another when i send an atom as a message ? My thinking is that since this atom is already existing in the VM is doesnot have to make a copy. I understand that binaries are more efficient when sending from one process to another.

If i am sending a trigger message, a constant message from one process to another, which is better to use: atom or binary ?

like image 978
Muzaaya Joshua Avatar asked Jan 07 '23 15:01

Muzaaya Joshua


1 Answers

Use what is the most correct semantically. In general, don't worry about performance unless you have benchmarked and you are certain your code could benefit from optimizations. If you use what is the most correct semantically, it will likely be the fastest anyway.

That said, what is the most correct semantically?

Atoms are useful for tagging or identifying terms that are static, that won't change. So if you want to tell a process to do some work, you could write: send(pid, :do_some_work). Then the other process can easily match on the atom and perform the required work (comparison with atoms are super fast).

However, if you are passing dynamic content, then surely you want to use binaries. It would actually be unsafe to convert binaries to atoms and atoms also have a size limit. You can't have an atom that is 1 kilobyte long.

Finally, it is worth pointing out that atoms are by far the fastest to copy. Atoms are represented as integers, they take 1 word. So you are copying just 1 word around.

Binaries, even though they are shared after a certain size, take at least 3 words.

More information: Why is useful to have a atom type (like in elixir, erlang)?

The Erlang VM efficiency guide: http://www.erlang.org/doc/efficiency_guide/advanced.html

like image 109
José Valim Avatar answered Mar 15 '23 21:03

José Valim