Skip to content

perf: pre-compile regex in RegexMatch for better performance#1721

Open
Herrtian wants to merge 1 commit intoapache:masterfrom
Herrtian:perf/precompile-regex-in-regexmatch
Open

perf: pre-compile regex in RegexMatch for better performance#1721
Herrtian wants to merge 1 commit intoapache:masterfrom
Herrtian:perf/precompile-regex-in-regexmatch

Conversation

@Herrtian
Copy link
Copy Markdown

Summary

Ref #1690

RegexMatch() used regexp.MatchString() which recompiles the regex pattern on every single invocation. This is a performance bottleneck since RegexMatch is called by KeyMatch2, KeyMatch3, KeyMatch5, and can be used directly in policy matchers.

Change

Replaced regexp.MatchString() with the existing mustCompileOrGet() cache that is already used throughout the codebase for other KeyMatch functions. The compiled regex is cached in a thread-safe map and reused on subsequent calls.

// Before: recompiles regex on every call
func RegexMatch(key1 string, key2 string) bool {
    res, err := regexp.MatchString(key2, key1)
    if err != nil {
        panic(err)
    }
    return res
}

// After: uses cached compiled regex
func RegexMatch(key1 string, key2 string) bool {
    return mustCompileOrGet(key2).MatchString(key1)
}

Test plan

  • go build ./... passes
  • go test ./... — all tests pass
  • go test ./util/... — all util tests pass including regex match tests

🤖 Generated with Claude Code

RegexMatch() called regexp.MatchString() which recompiles the pattern on
every invocation. Use the existing mustCompileOrGet() cache instead.

Ref apache#1690
@Herrtian Herrtian force-pushed the perf/precompile-regex-in-regexmatch branch from 4f91d7c to f4fa290 Compare April 15, 2026 17:54
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