Optimize Gem::Text#format_text performance#9430
Open
apocalypse9949 wants to merge 1 commit intoruby:masterfrom
Open
Optimize Gem::Text#format_text performance#9430apocalypse9949 wants to merge 1 commit intoruby:masterfrom
apocalypse9949 wants to merge 1 commit intoruby:masterfrom
Conversation
Author
| Opened a clean PR with only the intended changes from #9418 |
Member
| Can you share the benchmark result? |
kou reviewed Mar 25, 2026
Author
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.

The$O(N^2)$ time complexity. This was due to the use of
Gem::Text#format_textmethod contained a performance bottleneck that caused it to run with anString#slice!(0, length)inside awhileloop to iteratively strip chunks from the beginning of theworkstring.Because
String#slice!modifies the string in-place, it requires shifting the remaining characters in memory to the left during every iteration. When processing very long strings (such as maliciously crafted gem descriptions), the repeated memory shifting leads to excessive CPU usage and a potential Denial of Service (DoS) vulnerability.This PR resolves the performance bottleneck by refactoring
format_textto use non-destructive string slicing (String#slice) combined with reassignment (work = work.slice(...)).Ruby optimizes$O(N)$ .
String#sliceusing a shared string buffer (copy-on-write), meaning it simply creates a new string object that points to an offset within the original buffer rather than duplicating the entire buffer. This prevents the memory-shifting overhead and effectively reduces the time complexity to