Are there any advantages using maps instead of records to hold state in Erlang processes?

时间:2015-07-31 20:28:25

标签: erlang

Most of the books or online resources I've seen are all using records to hold the state of a process (probably because that was the way for more(?) than a decade). On the other hand, maps are effectively used to replace tuples in stdlib (for example childspecs in the supervisor module).

As an example, I am working my way through Learn You Some Erlang's Finite State Machines chapter and the state record could be replaced with a map, declared in the init/1 callback needed by gen_fsm.

  • The record declaration won't be needed and most of what I've read so far, a best practice is to keep them local anyway as .hrl files make it harder to track errors.
  • Referring to the process state in function clauses would also be shorter but they both clearly convey the structure of the state variable and a couple extra characters are not a concern.

Also, would it be more efficient?
I know that a well-thought out benchmark would answer my question but I am only a couple weeks into learning Erlang and the maps module is fairly new and still changing.

UPDATE: Thanks to I GIVE TERRIBLE ADVICE, I read the LYSE chapter on maps more thoroughly and the answer is clear:

Using records has the advantage that the keys are known at compile time that brings advantages of

  • fast access to specific values (faster than what is possible dynamically)
  • additional safety (crash early rather than corrupting state)
  • easier type checking

These make records absolutely appropriate for a process' internal state, despite the occasional burden of writing a more verbose code_change function.

On the other hand, where Erlang users would use records to represent complex nested key/value data structures (oddly similar to objects in object-oriented languages) that would frequently cross module boundaries, maps will help a lot. Records were the wrong tool for that job.

2 个答案:

答案 0 :(得分:4)

我已经在了解你一些Erlang 网站上添加了一章专门介绍地图:http://learnyousomeerlang.com/maps

Mexican Standoff 部分专门将地图与记录和词组进行比较。从语义上讲,地图与记录更相似,而我的建议实际上是使用记录有意义的记录(具有O(1)访问权限的已知类型的受限密钥集),以及您拥有的地图使用dicts(异构的,灵活的键/值对集合)。

答案 1 :(得分:0)

作为Joe Armstrong said

  

记录已经死了 - 长期实时地图!

  

我们一直在讨论地图超过12年,但现在它们已经存在   留下来。

     

为什么漫长的等待? - 我们希望地图能够替代记录   并且要像记录一样高效,而且它的表现并不明显   这样做。

所以,看起来地图还可以,我们已经将项目从记录切换到地图,我们感觉不到任何性能损失。

一个限制: 如果我是对的,你不能在mnesia中存储地图,因为你可以用记录来存储。