perf: pre-compile regex in RegexMatch for better performance by Herrtian · Pull Request #1721 · apache/casbin · GitHub
Skip to content

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

Merged
nodece merged 1 commit into
apache:masterfrom
Herrtian:perf/precompile-regex-in-regexmatch
May 6, 2026
Merged

nodece merged 1 commit into
apache:masterfrom
Herrtian:perf/precompile-regex-in-regexmatch

Conversation

@Herrtian

Copy link
Copy Markdown
Contributor

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 #1690
@github-actions

Copy link
Copy Markdown

@nodece
nodece merged commit 12ac0c9 into apache:master May 6, 2026
5 checks passed
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.

2 participants