Skip to content

Fix quadratic time of match function in the number of matches - #337

Closed
chiliec wants to merge 1 commit into
itchyny:mainfrom
chiliec:fix-match-quadratic
Closed

chiliec wants to merge 1 commit into
itchyny:mainfrom
chiliec:fix-match-quadratic

Conversation

@chiliec

@chiliec chiliec commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

The match function recomputed each match's rune offset by counting runes from the start of the string (len([]rune(s[:x]))), so the work grew quadratically with the number of matches. This also slowed splits, sub, and gsub, which build on match.

This tracks a byte/rune cursor and advances it across the already-sorted match indices, making the offset computation linear. Output is unchanged.

Fixes #336

Verified with the issue's repro: on "<a>é " * n, [match("<"; "g")] went from 70/273/1084/3946/16049 ms (n=2000..32000, ~4x per doubling) to 14/15/23/45/77 ms (linear). go test ./... passes and outputs match the previous build on multibyte, empty-match, and capture-group cases.

funcMatch recomputed the rune offset of each match by counting runes
from the start of the string, which is O(n^2) in the number of matches.
Track a byte/rune cursor and advance it across the already-sorted
indices instead. This also speeds up splits, sub, and gsub.

Fixes itchyny#336
@itchyny

itchyny commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Fixed by #338.

@itchyny itchyny closed this Nov 17, 2026
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.

match, splits, and sub/gsub take quadratic time in the number of matches

2 participants