并String.to_atom("some-known-string")创建一个新的原子的原子表中的每个时间?
如果没有,那又有什么意义String.to_existing_atom/1呢?
如果是,那么为什么?因为String.to_atom("some-known-string")总会得到相同的结果......并且atom-table 永远不会被垃圾收集
假设您总是使用相同的字符串,它可能只在第一次运行时创建一个新的原子.之后,假设继续使用相同的字符串,它将不会创建新的原子.
还有一个原因to_existing_atom是为了防止用未知信息填充原子表.
iex(1)> String.to_existing_atom("foo")
** (ArgumentError) argument error
:erlang.binary_to_existing_atom("foo", :utf8)
iex(1)> String.to_atom("foo")
:foo
iex(2)> String.to_existing_atom("foo")
:foo
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,当我第一次尝试调用时to_existing_atom,该进程实际上崩溃了,因为该原子不在原子表中.但是,如果我用to_atom它来确保它存在,我现在可以打电话to_existing_atom,我不会崩溃.