Skip to content

Commit a564c2e

Browse files
authored
Optimize Enum.flat_map/2 for filtering (#13793)
1 parent 27b894c commit a564c2e

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

lib/elixir/lib/enum.ex

+6
Original file line numberDiff line numberDiff line change
@@ -1266,13 +1266,16 @@ defmodule Enum do
12661266
def flat_map(enumerable, fun) do
12671267
reduce(enumerable, [], fn entry, acc ->
12681268
case fun.(entry) do
1269+
[] -> acc
12691270
list when is_list(list) -> [list | acc]
12701271
other -> [to_list(other) | acc]
12711272
end
12721273
end)
12731274
|> flat_reverse([])
12741275
end
12751276

1277+
# the first clause is an optimization
1278+
defp flat_reverse([[elem] | t], acc), do: flat_reverse(t, [elem | acc])
12761279
defp flat_reverse([h | t], acc), do: flat_reverse(t, h ++ acc)
12771280
defp flat_reverse([], acc), do: acc
12781281

@@ -4425,6 +4428,9 @@ defmodule Enum do
44254428

44264429
defp flat_map_list([head | tail], fun) do
44274430
case fun.(head) do
4431+
# the two first clauses are an optimization
4432+
[] -> flat_map_list(tail, fun)
4433+
[elem] -> [elem | flat_map_list(tail, fun)]
44284434
list when is_list(list) -> list ++ flat_map_list(tail, fun)
44294435
other -> to_list(other) ++ flat_map_list(tail, fun)
44304436
end

0 commit comments

Comments
 (0)