Skip to content

perf: add fast-path for static routes in Router::checkRoutes() - #10705

Open
gr8man wants to merge 1 commit into
codeigniter4:developfrom
gr8man:perf/router-static-fast-path
Open

gr8man wants to merge 1 commit into
codeigniter4:developfrom
gr8man:perf/router-static-fast-path

Conversation

@gr8man

@gr8man gr8man commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Description
In Router::checkRoutes(), every registered route was unconditionally evaluated with preg_match('#^' . $routeKey . '$#u', $uri, $matches). In applications with dozens or hundreds of routes, matching routes located later in the table (or handling 404s) incurs significant PCRE overhead.

This PR adds a fast-path for static routes:

  • Uses strpbrk($routeKey, "()[]?*+{}^$\.|#") to detect PCRE metacharacters (including the pattern delimiter #).
  • If no metacharacters are present, directly compares $routeKey !== $uri and skips PCRE execution.
  • If $routeKey === $uri, initializes $matches = [$uri] and proceeds directly to dispatch.
  • Strictly preserves route definition order and evaluation precedence (dynamic routes registered before matching static patterns retain priority).
  • Preserves all existing behavior for Closures, controllers, parameters, redirects, and locales with zero BC breaks.

Benchmark (10,000 iterations per scenario)

  • 100 routes (mixed table, match at position 100): ~46.8% latency reduction (1.88x speedup)
  • 100 routes (purely static, match at position 100): ~44.3% latency reduction (1.80x speedup)
  • 100 routes (match at position 1): ~35.2% latency reduction (1.54x speedup)

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value (without duplication)
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

Avoid executing PCRE for static routes by checking for PCRE metacharacters
(including pattern delimiter '#') using strpbrk(). If none are present,
perform a direct string comparison against the request URI.

This reduces matching overhead from O(N) PCRE invocations to O(1) string
checks for static routes while strictly preserving registration precedence
and existing handler, Closure, redirect, and locale behavior.
@carson-codeigniter4 carson-codeigniter4 Bot added the enhancement PRs that improve existing functionalities label Nov 1, 2026

This branch has not been deployed

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

Labels

enhancement PRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant