Elixir Enum.map vs For comprehension

Tan*_*ano 3 functional-programming elixir

I have a map and I am modifying each element on it, I am confused which approach is better(faster) to do it with Enum.map and then Enum.into(%{}) or to use for comprehension like

for {key, value} <- my_map, into: %{} do
  {key, new_value}
end
Run Code Online (Sandbox Code Playgroud)

sba*_*rob 5

您可以使用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
Run Code Online (Sandbox Code Playgroud)

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

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