Elixir Enum.map vs理解

时间:2019-03-07 07:56:20

标签: functional-programming elixir

我有一张地图,我正在修改它上的每个元素,我感到困惑的是哪种方法更好(更快)先用Enum.map然后再用Enum.into(%{})来完成,或者用于理解

for {key, value} <- my_map, into: %{} do
  {key, new_value}
end

1 个答案:

答案 0 :(得分:4)

您可以使用Benchee进行这种比较。

一个简单的Benchee测试将显示Enum在这种情况下更快。

iex(1)> m = %{a: 1, b: 2, c: 3, d: 4}
%{a: 1, b: 2, c: 3, d: 4}
iex(2)> with_enum = fn -> Enum.map(m, fn {k, v} -> {k, v * v} end) end
#Function<20.127694169/0 in :erl_eval.expr/5>
iex(3)> with_for = fn -> for {k, v} <- m, into: %{}, do: {k, v * v} end
#Function<20.127694169/0 in :erl_eval.expr/5>
iex(4)> Benchee.run(%{
...(4)>   "with_enum" => fn -> with_enum.() end,
...(4)>   "with_for" => fn -> with_for.() end
...(4)> })
Operating System: Linux
CPU Information: Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz
Number of Available Cores: 4
Available memory: 7.71 GB
Elixir 1.7.4
Erlang 21.0

Benchmark suite executing with the following configuration:
warmup: 2 s
time: 5 s
memory time: 0 ns
parallel: 1
inputs: none specified
Estimated total run time: 14 s


Benchmarking with_enum...
Benchmarking with_for...

Name                ips        average  deviation         median         99th %
with_enum       28.27 K       35.37 μs    ±16.16%       34.37 μs       55.21 μs
with_for        19.55 K       51.14 μs     ±9.16%       50.08 μs       59.94 μs

Comparison: 
with_enum       28.27 K
with_for        19.55 K - 1.45x slower

通常,for并不是Elixir中这些情况的最佳选择,它最适合列表推导,它可以非常快速地执行并且语法易于阅读。

Enum的功能经过优化,可以处理这些更迭代的情况,例如您使用其他编程语言中的for构造所做的事情。