LoginSignup
5
3

More than 5 years have passed since last update.

binary_to_atom/2 は使わない!! #Erlang

Posted at

Erlangで…
binary_to_atom/2は使わない!!

以上

だけではよくわからないと思うので、、、

理由

Data type Memory size
Atom 1 word. Note: an atom refers into an atom table which also consumes memory. The atom text is stored once for each unique atom in this table. The atom table is not garbage-collected.

何が来るかわからない binary()全て atom() に変えていたらメモリが開放されないのでメモリが足りなくなります。
なので、Erlangをよく知っていて大丈夫だと思って使う場合以外は使わないようにしましょう。
(僕も結構Erlangを書いていると思っていますが、 binary_to_atom/2 は使っていません。)

参考URL: http://www.erlang.org/doc/efficiency_guide/advanced.html#id68923

それでも binary()atom() にしたい/しなければならない場合は…

それでも外部から受け取った binary() を内部で atom() として使用する場面があると思います。その時は、 binary_to_existing_atom/2 を使いましょう。

binary_to_existing_atom(Binary, Encoding) -> atom()

Types:

Binary = binary()
Encoding = latin1 | unicode | utf8
Works like binary_to_atom/2, but the atom must already exist.

Failure: badarg if the atom does not already exist.

この関数では、今変換しようとしている Binaryatom() として既に存在している場合は atom() に変換して存在しない場合は例外を投げます。

基本的にはErlangで atom() を使用したい場合、パターンマッチで使うため、既にコード内に atom() で存在しているため、この関数でもやりたいことを満たせるはずです。

変換後の atom() がコードの中にないという場合は、そもそもそのコードを見直したほうがいいかもしれません。(このほとんどの場合は atom() にする必要がないのではないかと思われる)
(変換後の atom() がコードの どこかに あった場合でもうまくいかない時がありますが、本題からそれるためここでは説明を省く。)

参考URL: http://erlang.org/doc/man/erlang.html#binary_to_existing_atom-2

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3