Skip to content

improve performance of splits, sub, and gsub by splitting the string natively - #339

Open
mandosavi wants to merge 1 commit into
itchyny:mainfrom
mandosavi:fix/splits-sub-quadratic
Open

mandosavi wants to merge 1 commit into
itchyny:mainfrom
mandosavi:fix/splits-sub-quadratic

Conversation

@mandosavi

@mandosavi mandosavi commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

splits, split/2, sub, and gsub take quadratic time in the number of matches (#336). They are defined in jq on top of match, and for every match they slice the input by codepoint index, which scans the string from the beginning. sub also appends to the result string for every match, which copies it each time.

This adds an internal function _splits that splits the string at the matches using the byte indices of the regexp, and optionally returns the named captures of each match. splits and split/2 call it directly. sub collects the replacement pieces in arrays and joins them once at the end.

In-process timings on "<a>é " repeated n times (go1.27.3, linux/amd64):

before after
[splits("<")], n = 8000 1157 ms 3.3 ms
[splits("<")], n = 64000 74.8 s 28 ms
gsub("<"; "["), n = 8000 1217 ms 10 ms
gsub("<"; "["), n = 64000 73.9 s 81 ms

The total allocation of gsub at n = 64000 goes from 12.7 GB to 37 MB (peak memory from 72 MB to 32 MB). On a 1.4 MB HTML string with 80,000 < characters, [splits("<")] now takes 37 ms and gsub("<"; "&lt;") 105 ms.

The behavior does not change. Errors of splits and sub are still reported as match(...) cannot be applied to: .... I compared splits, split, sub, and gsub before and after this change on 2.8 million cases (random inputs including invalid UTF-8, non-string inputs, invalid flags and patterns, and replacement filters with multiple outputs, no outputs, errors, and non-string values), and the outputs and error messages are identical. The added tests cover replacements with a different number of outputs per match, unmatched named captures, and multibyte input.

This is the second part of #336 and does not depend on #338, which covers match. Together they cover everything in the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant