perf: optimize KeyMatch functions with fast path for wildcard replacement by knyk-dev · Pull Request #1699 · apache/casbin · GitHub
Skip to content

perf: optimize KeyMatch functions with fast path for wildcard replacement - #1699

Closed
knyk-dev wants to merge 1 commit into
apache:masterfrom
knyk-dev:builtin-op-test
Closed

knyk-dev wants to merge 1 commit into
apache:masterfrom
knyk-dev:builtin-op-test

Conversation

@knyk-dev

Copy link
Copy Markdown
Contributor

This pull request optimizes the performance of path matching functions in the utility package.

  • The casbin library heavily relies on functions like KeyMatch2 through KeyMatch5 for policy enforcement.
  • Profiling analysis revealed that strings.Replace was executing unconditionally, consuming unnecessary CPU cycles.
  • We implemented a fast path check using strings.Contains to verify wildcard existence before attempting replacement.
  • This engineering change effectively reduces overhead for keys that do not require modification.
  • The optimization is validated against upstream benchmarks, specifically BenchmarkRBACModelWithDomainPatternLarge .
  • Linter directives //nolint:gosimple are added to explain the intentional code structure for performance gains.

…ment

This change introduces a fast path optimization for KeyMatch2, KeyMatch3, KeyMatch4, KeyMatch5 and their corresponding KeyGet functions.

Original code (unconditional replacement):
key2 = strings.Replace(key2, "/*", "/.*", -1)

Optimized code (conditional replacement):
if strings.Contains(key2, "/*") { //nolint:gosimple // optimization
    key2 = strings.Replace(key2, "/*", "/.*", -1)
}

This avoids unnecessary allocations and processing when the key does not contain a wildcard, as verified by upstream benchmarks using test data like 'examples/performance/rbac_with_pattern_large_scale_policy.csv'.
@github-actions

Copy link
Copy Markdown

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