erlang - 在 Erlang 进程中使用映射而不是记录来保存状态有什么优势吗?

标签 erlang

我见过的大多数书籍或在线资源都使用记录来保存进程的状态(可能是因为这是十多年来(?)的方式)。另一方面,映射有效地用于替换 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/

    相关文章:

    使用 mochiweb 对列表进行 JSON 编码

    erlang - Erlang 中缺少可变参数的解决方法

    erlang - 当我向 Erlang 中的已失效进程发送消息时会发生什么?

    Erlang子列表函数性能

    erlang - 什么是 Erlang 节点?

    python - 如何使用python执行erlang命令

    erlang - 在Erlang中使用大量的尾递归是否会减慢它的速度?

    erlang - Erlang VM (BEAM) 是如何构造列表的?

    multithreading - Erlang的抽象机BEAM中使用了哪些OS线程?

    tcp - 如何检测 tcp 客户端与 gen_tcp 断开连接?