我见过的大多数书籍或在线资源都使用记录来保存进程的状态(可能是因为这是十多年来(?)的方式)。另一方面,映射有效地用于替换 stdlib 中的元组(例如 childspecs in the supervisor module )。
例如,我正在通过 Learn You Some Erlang's Finite State Machines 工作。章和state
记录可以用 map 替换,在 init/1
中声明gen_fsm
需要的回调.
.hrl
文件使跟踪错误变得更加困难。 另外,这样效率会更高吗?
我知道一个经过深思熟虑的基准测试会回答我的问题,但我只有几周的时间学习 Erlang 和 maps module相当新,仍然changing .
更新:感谢我提供了糟糕的建议,我阅读了 LYSE chapter on maps更彻底,答案很明确:
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.
最佳答案
我在 Learn You Some Erlang 网站上专门添加了一章关于 map 的内容:http://learnyousomeerlang.com/maps
墨西哥对峙部分专门将 map 与记录和字典进行比较。从语义上讲,映射比记录更类似于字典,我的建议实际上是使用记录有意义的记录(具有 O(1) 访问权限的已知类型的受限键集),以及使用字典的映射(异构的、灵活的键/值对集)。
关于erlang - 在 Erlang 进程中使用映射而不是记录来保存状态有什么优势吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31754667/