Skip to content

Commit f9ac0d8

Browse files
precizSteffenDE
authored andcommitted
Optimize class_attribute_list/1 using an IO data tree (#4172)
Instead of producing intermediate flat lists and joining them via string concatenation using Enum.flat_map/2 and Enum.join/2, this recursive approach builds a deeply nested IO data tree. It evaluates ~1.5x faster and produces significantly less garbage collection pressure since intermediate strings for spaces and joined binaries are no longer allocated.
1 parent bfd8d93 commit f9ac0d8

1 file changed

Lines changed: 11 additions & 9 deletions

File tree

lib/phoenix_live_view/html_engine.ex

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -175,17 +175,19 @@ defmodule Phoenix.LiveView.HTMLEngine do
175175
def class_attribute_encode(other),
176176
do: empty_attribute_encode(other)
177177

178-
defp class_attribute_list(value) do
179-
value
180-
|> Enum.flat_map(fn
181-
nil -> []
182-
false -> []
183-
inner when is_list(inner) -> [class_attribute_list(inner)]
184-
other -> [other]
185-
end)
186-
|> Enum.join(" ")
178+
defp class_attribute_list(list), do: class_attribute_list(list, [])
179+
180+
defp class_attribute_list([], acc), do: acc
181+
defp class_attribute_list([nil | t], acc), do: class_attribute_list(t, acc)
182+
defp class_attribute_list([false | t], acc), do: class_attribute_list(t, acc)
183+
184+
defp class_attribute_list([h | t], acc) when is_list(h) do
185+
class_attribute_list(t, class_attribute_list(h, acc))
187186
end
188187

188+
defp class_attribute_list([h | t], []), do: class_attribute_list(t, [to_string(h)])
189+
defp class_attribute_list([h | t], acc), do: class_attribute_list(t, [acc, " ", to_string(h)])
190+
189191
@doc false
190192
def empty_attribute_encode(nil), do: ""
191193
def empty_attribute_encode(false), do: ""

0 commit comments

Comments
 (0)