Optimize HTMLTree.to_tuple_list/1 using tail recursion#670
Merged
Conversation
Replace `Enum.reduce/3` with a custom private tail-recursive function (`do_to_tuple_list/3`) in `Floki.HTMLTree.to_tuple_list/1` and `to_tuple/2`. This avoids anonymous function allocation for every children list and skips the `Enum` protocol dispatch overhead. Because the internal IDs (`root_nodes_ids` and `children_nodes_ids`) are stored natively in reverse document order, iterating over them and prepending to an accumulator (`[to_tuple(...) | acc]`) inherently builds the resulting list of tuples in the correct document order without needing any explicit `Enum.reverse/1` calls. Performance improvements in extracting the raw HTML tuples from the tree: - Small HTML: ~26% faster, ~29% less memory - Medium HTML: ~14% faster, ~29% less memory - Big HTML: ~13% faster, ~28% less memory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Replace
Enum.reduce/3with a custom private tail-recursive function(
do_to_tuple_list/3) inFloki.HTMLTree.to_tuple_list/1andto_tuple/2.~15% faster & 30% less memory usage