Jaypee
Is this a correct way to avoid wasting or reaching the atom limit?
As I have to generate several atoms from strings and as atoms are not garbage collected and there’s a limit for each process, does this function is correct to “save” them atoms ? :
def string_to_atom(str) do
try do
String.to_existing_atom(str)
rescue
ArgumentError -> String.to_atom(str)
end
end
Or do you know any smarter (or “elixier”) way to achieve this (perhaps without this ugly “try rescue”) ?
Most Liked
rvirding
As others have already pointed out there is only one truly safe way to handle dynamically creating atoms and that is DON’T. Even if you feel you must: don’t. Even if it is only occasionally: don’t.
LostKobrakai
I’m not really sure how this would be safer than just using String.to_atom(str). String.to_atom(str) does not create a new atom, if one already exists for the given name. Atoms are basically put in a table mapping a name to a number (which makes them so quick e.g. to compare), so there can never be multiple entries for the same name. The problem is not that, but plain too many names in said table. What you have above doesn’t guard against that at all.
Also the limit in atoms is not per process, but it’s global to the vm. The atom table is never cleaned up (and probably can’t be) and it simply takes memory. Once it grows enough there might not be enough memory left for all the other things your vm does.
rvirding
OK, I will qualify that and add “unless you know there will only be a few new atoms”. Recreating existing atoms is ok as that just reuses them.
Popular in Questions
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
- #performance









