Skip to content

Optimize Gem::Text#format_text performance#9430

Open
apocalypse9949 wants to merge 1 commit intoruby:masterfrom
apocalypse9949:master
Open

Optimize Gem::Text#format_text performance#9430
apocalypse9949 wants to merge 1 commit intoruby:masterfrom
apocalypse9949:master

Conversation

@apocalypse9949
Copy link

The Gem::Text#format_text method contained a performance bottleneck that caused it to run with an $O(N^2)$ time complexity. This was due to the use of String#slice!(0, length) inside a while loop to iteratively strip chunks from the beginning of the work string.

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_text to use non-destructive string slicing (String#slice) combined with reassignment (work = work.slice(...)).

Ruby optimizes String#slice using 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 $O(N)$.

@apocalypse9949
Copy link
Author

Opened a clean PR with only the intended changes from #9418

@hsbt
Copy link
Member

hsbt commented Mar 25, 2026

Can you share the benchmark result?

@apocalypse9949
Copy link
Author

Screenshot 2026-03-26 082624
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants