【问题标题】:Performance of selective `receive` in Elixir/ErlangElixir/Erlang 中选择性“接收”的性能
【发布时间】:2017-11-28 21:08:00
【问题描述】:

当我有这样的代码时:

receive do
  {:hello, msg} -> msg
end

假设我的邮箱中有N 消息。查找此特定消息的性能是O(1)O(N),还是介于两者之间?

【问题讨论】:

  • 不是 O(1)。另外,假设您的接收中有 N 个子句? O(N-shite)?
  • 除了所有这些关于选择性接收的复杂性/性能的讨论(这显然是模式数量、它们的复杂性以及在某些情况下消息数量的函数)之外,不要忘记一个好的设计应该限制子句的数量,促进模式匹配(例如使用格式 {Tag,Rest}),并且消息队列的理想大小为 0(因此垃圾消息)。

标签: erlang elixir


【解决方案1】:

性能将线性增长,与邮箱中的元素数量成正比,因此为 O(N)。

【讨论】:

【解决方案2】:

Receive 对消息框进行线性扫描,然后返回第一个匹配的消息框。有一个例外(自R14A

OTP-8623  == compiler erts hipe stdlib ==

    Receive statements that can only read out a newly created
    reference are now specially optimized so that it will execute
    in constant time regardless of the number of messages in the
    receive queue for the process. That optimization will benefit
    calls to gen_server:call(). (See gen:do_call/4 for an example
    of a receive statement that will be optimized.)

所以在你的情况下它是 O(N) 操作。

【讨论】:

    【解决方案3】:

    Erlang 中的消息传递,也就是 Elixir,是“先进先出”的。您一个一个地浏览它们,第一个满足receive 中的任何子句的都会被处理。在最坏的情况下,您可能会阻塞您的消息框。

    【讨论】:

      猜你喜欢
      • 2012-06-13
      • 2019-12-25
      • 2020-09-11
      • 2020-09-30
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多