Skip to content

Commit e9a8c63

Browse files
gustflexmag
authored andcommitted
Optimize Enum.reduce/3 for ranges (#5477)
1 parent 66624e7 commit e9a8c63

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

lib/elixir/lib/enum.ex

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1756,7 +1756,11 @@ defmodule Enum do
17561756
end
17571757

17581758
def reduce(first..last, acc, fun) when is_function(fun, 2) do
1759-
reduce_range(first, last, acc, fun, last >= first)
1759+
if first <= last do
1760+
reduce_range_inc(first, last, acc, fun)
1761+
else
1762+
reduce_range_dec(first, last, acc, fun)
1763+
end
17601764
end
17611765

17621766
def reduce(%{__struct__: _} = enumerable, acc, fun) when is_function(fun, 2) do
@@ -1773,16 +1777,20 @@ defmodule Enum do
17731777
fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)
17741778
end
17751779

1776-
defp reduce_range(x, y, acc, fun, true) when x <= y do
1777-
reduce_range(x + 1, y, fun.(x, acc), fun, true)
1780+
defp reduce_range_inc(first, first, acc, fun) do
1781+
fun.(first, acc)
17781782
end
17791783

1780-
defp reduce_range(x, y, acc, fun, false) when x >= y do
1781-
reduce_range(x - 1, y, fun.(x, acc), fun, false)
1784+
defp reduce_range_inc(first, last, acc, fun) do
1785+
reduce_range_inc(first + 1, last, fun.(first, acc), fun)
17821786
end
17831787

1784-
defp reduce_range(_, _, acc, _, _) do
1785-
acc
1788+
defp reduce_range_dec(first, first, acc, fun) do
1789+
fun.(first, acc)
1790+
end
1791+
1792+
defp reduce_range_dec(first, last, acc, fun) do
1793+
reduce_range_dec(first - 1, last, fun.(first, acc), fun)
17861794
end
17871795

17881796
@doc """

0 commit comments

Comments
 (0)