Optimize FlatText.get/3 memory usage and speed#664
Merged
philss merged 3 commits intophilss:mainfrom Mar 17, 2026
Merged
Conversation
Replaced Enum.reduce/3 with an optimal tail-recursive approach in FlatText. By traversing lists manually, we avoid the overhead of the Enumerable protocol and the allocation of anonymous closures per reduction iteration. Benchmark results when running Floki.FlatText.get on a large document: ```text Name ips average deviation median 99th % Tail recursion 3.21 M 311.16 ns ±23057.88% 50 ns 160 ns Enum.reduce 2.76 M 361.71 ns ±20499.20% 50 ns 180 ns Comparison: Tail recursion 3.21 M Enum.reduce 2.76 M - 1.16x slower +50.55 ns Memory usage statistics: Name Memory usage Tail recursion 136 B Enum.reduce 208 B - 1.53x memory usage +72 B ```
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.
Optimizes shallow text extraction in
Floki.FlatTextby replacingEnum.reduce/3with a direct tail-recursive approach.Performance Impact:
Across various Benchee tests (Small/Medium/Large HTML, and highly nested lists), this approach yields:
Tests:
Adds a comprehensive set of edge-case tests to
flat_text_test.exs(covering deeply nested nodes, mixed tuples, and sequential text) to guarantee 100% behavioral parity with the previous implementation and protect against regressions.