Repository navigation
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Strict equality skips previously matching routes for URIs ending in an allowed newline, potentially sending requests to a catch-all or 404; preserve regex handling for this case and add a regression test.
1 open issue
What changed in this PR
Optimizes CodeIgniter’s route matching by bypassing regular expressions for static route keys while retaining ordered route evaluation.
Changes:
- Adds direct string comparison for routes without regex metacharacters.
- Keeps shared dispatch logic for static and dynamic matches.
- Adds tests for controllers, closures, numeric keys, additional segments, and dynamic-route precedence.
Assumed target: develop, since no base branch is specified. Validation used focused code inspection; automated tests remain for CI.
| File | Description |
|---|---|
tests/system/Router/RouterTest.php |
Adds static-route matching and precedence tests. |
system/Router/Router.php |
Introduces the static-route fast path and shared dispatch flow. |
Review effort: Balanced
paulbalandan
left a comment
There was a problem hiding this comment.
Please delete comments that just explain what the code is doing, instead of why is it doing that way.
| // Does the RegEx match? | ||
| if (! preg_match('#^' . $routeKey . '$#u', $uri, $matches)) { |
There was a problem hiding this comment.
| // Does the RegEx match? | |
| if (! preg_match('#^' . $routeKey . '$#u', $uri, $matches)) { | |
| if (preg_match('#^' . $routeKey . '$#u', $uri, $matches) !== 1) { |
9a4d4ab to
893f1e1
Compare
paulbalandan
left a comment
There was a problem hiding this comment.
Please preserve matching for URIs ending in a permitted newline. With permittedURIChars = '', a route for about-us previously matched handle('about-us%0A'); the current comparison returns 404 instead. I reproduced this on the current revision.
Keep the regex path for this case and add a regression test. This targets develop, so the optimization should preserve existing matching behavior.
Also, my earlier suggestion to use preg_match(...) !== 1 is still missing.
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.
The static fast-path compared the route key with ===, which dropped matches the `$` anchor used to accept for a URI ending in LF, sending those requests to a catch-all or a 404. Fall back to PCRE when the URI ends with LF, and add regression tests for LF and CRLF URIs. Also compare preg_match() against 1, as requested in review.
The dropped comments only repeated what the following lines do. The ones that explain why the code works this way, including the metacharacter list and the trailing-LF fallback, are kept.
The handler doubles as the preg_replace() replacement in the single-segment mode, which is not obvious from the call alone.
ccb01ce to
d94c9d3
Compare
michalsn
left a comment
There was a problem hiding this comment.
Please extend the benchmark to compare the base branch against this PR for static-only, mixed static/dynamic, and dynamic-only routes.
For each case, please include matching the first and last route, as well as a request with no matching route. It would be useful to run this with the minimum PHP version, and share the benchmark script and runtime settings.
Since strpbrk() now runs for every route, including dynamic routes that still require preg_match(), we should measure both the gains and the added overhead before merging.
Benchmark:
|
| table | match | old µs/op | new µs/op | Δ µs | Δ % | speedup |
|---|---|---|---|---|---|---|
| static | first | 13.567 | 13.389 | −0.178 | −1.3% | 1.013× |
| static | last | 61.080 | 57.213 | −3.867 | −6.3% | 1.068× |
| static | none | 52.339 | 51.328 | −1.012 | −1.9% | 1.020× |
| mixed | first | 6.674 | 6.854 | +0.180 | +2.7% | 0.974× |
| mixed | last | 29.605 | 33.718 | +4.113 | +13.9% | 0.878× |
| mixed | none | 27.574 | 32.049 | +4.475 | +16.2% | 0.860× |
| dynamic | first | 6.512 | 6.733 | +0.221 | +3.4% | 0.967× |
| dynamic | last | 30.164 | 43.275 | +13.111 | +43.5% | 0.697× |
| dynamic | none | 28.227 | 40.301 | +12.075 | +42.8% | 0.700× |
Results — PHP 8.5.4
| table | match | old µs/op | new µs/op | Δ µs | Δ % | speedup |
|---|---|---|---|---|---|---|
| static | first | 27.266 | 27.328 | +0.062 | +0.2% | 0.998× |
| static | last | 111.850 | 104.286 | −7.564 | −6.8% | 1.073× |
| static | none | 51.006 | 47.823 | −3.183 | −6.2% | 1.067× |
| mixed | first | 13.386 | 13.690 | +0.304 | +2.3% | 0.978× |
| mixed | last | 55.194 | 64.242 | +9.048 | +16.4% | 0.859× |
| mixed | none | 51.978 | 60.877 | +8.899 | +17.1% | 0.854× |
| dynamic | first | 12.976 | 13.271 | +0.294 | +2.3% | 0.978× |
| dynamic | last | 55.449 | 72.796 | +17.348 | +31.3% | 0.762× |
| dynamic | none | 51.763 | 69.331 | +17.568 | +33.9% | 0.747× |
Control run on develop (old == new) — harness validation
Same harness, but both halves are the same source, so every delta must be noise:
| runtime | max |Δ%| over 9 scenarios |
|---|---|
| PHP 8.5.4 | 0.55% |
| PHP 8.2.35 | 1.03% |
A second full run on 8.5 reproduced 0.62%. Deltas below ~2% in the tables above are noise; all reported gains/regressions are far above it.
Why the check is a wash: measured primitive costs
| operation | cost |
|---|---|
preg_match('#^' . $key . '$#u', $uri) incl. concatenation |
190 ns |
| same match with the pattern already assembled | 129 ns |
| `strpbrk( |
#')` |
$key === $uri |
~2 ns |
For a literal key the PR replaces 190 ns with 128 + 2 ≈ 197 ns — no gain. For a regex key it adds 128 ns on top of the preg_match() that still has to run. The real checkRoutes() also pays ltrim() and str_ends_with() per iteration; this benchmark's baseline copy includes them.
Note: absolute µs include the shared RouteCollection::getRoutes() cost (it rebuilds the handler array on every call) and the dispatch tail; those are identical on both sides, so they dilute the percentages but do not bias them.
Benchmark script — A/B harness core
Full script: benchmarks/bench_router.php (890 lines). The measured code path:
<?php
declare(strict_types=1);
const BENCH_WARMUP = 200;
const BENCH_CHUNKS = 20;
const BENCH_MIN_ITERATIONS = 1000;
const BENCH_TABLES = ['static', 'mixed', 'dynamic'];
const BENCH_MATCHES = ['first', 'last', 'none'];
const BENCH_TABLE_NS = ['static' => 'static', 'mixed' => 'mix', 'dynamic' => 'dyn'];
const BENCH_BASELINE_SOURCE = 'develop@bdf459d24e8ee4ab895634733991c0c82baeb21d';
const BENCH_BASELINE_CHECKROUTES_SHA1 = '512c5a2b71d10876809024a808a2d9e2a6cdf0d6';
const BENCH_MISSING_PATH = ['static' => 'missing', 'mixed' => 'missing/42', 'dynamic' => 'missing/42'];
function routeKeyFor(string $table, int $index): string
{
if ($table === 'static') {
return 'static/' . $index;
}
if ($table === 'dynamic') {
return 'dyn/' . $index . '/(:num)';
}
// Interleaved: even positions are literal URIs, odd positions are regex
// routes - so position 1 (the "first" scenario) is dynamic.
return $index % 2 === 0 ? 'mix/' . $index : 'mix/' . $index . '/(:num)';
}
function buildRoutes(RouteCollection $collection, string $table, int $count): void
{
for ($i = 1; $i <= $count; $i++) {
// No `$1` back-references: handler expansion must cost the same on both
// implementations, otherwise the measurement would not isolate the diff.
$handler = 'Home::m' . $i;
assertHandlerResolvableByBaseline($handler);
$collection->get(routeKeyFor($table, $i), $handler);
}
}
function runScenario(array $opts, string $table, string $match): array
{
$count = $opts['count'];
$iterations = $opts['iterations'];
$reps = $opts['reps'];
// One collection, one request, two routers. checkRoutes() only reads the
// collection, so building the table once cannot favour either side, and
// both sides see byte-identical route data.
$collection = freshCollection();
buildRoutes($collection, $table, $count);
$request = service('request');
$old = new BenchBaselineRouter($collection, $request);
$new = new BenchCurrentRouter($collection, $request);
// RouteCollection::create() expands placeholders, so `(:num)` is stored as
// `([0-9]+)`. Derive the expected key positionally instead of rebuilding it.
$keys = array_keys($collection->getRoutes(Method::GET));
$expected = $match !== 'none';
$expectedKey = match ($match) {
'first' => $keys[0] ?? null,
'last' => $keys === [] ? null : $keys[count($keys) - 1],
default => null,
};
$uri = uriFor($table, $match, $count);
$routesTotal = count($keys);
if ($routesTotal !== $count) {
throw new RuntimeException(sprintf(
'Route table %s/%s registered %d routes, expected %d',
$table, $match, $routesTotal, $count,
));
}
// Bind once: rebinding inside the loop would measure Closure::bind() itself.
$runOld = Closure::bind(
function (string $uri): bool {
return $this->checkRoutes($uri);
},
$old,
BenchBaselineRouter::class,
);
$runNew = Closure::bind(
function (string $uri): bool {
return $this->checkRoutes($uri);
},
$new,
BenchCurrentRouter::class,
);
for ($i = 0; $i < BENCH_WARMUP; $i++) {
$runOld($uri);
$runNew($uri);
}
$repTimes = ['old' => [], 'new' => []];
$matchedRoutes = ['old' => null, 'new' => null];
// Each rep still executes `iterations` calls per implementation; the block
// is only split into chunks that alternate sides, because CPU frequency
// moves on a millisecond scale and a whole-block A/B charges every dip to
// whichever side ran during it (up to 12% fake delta on identical code).
$chunks = min(BENCH_CHUNKS, $iterations);
$chunkSize = intdiv($iterations, $chunks);
$tail = $iterations - $chunkSize * $chunks;
for ($r = 0; $r < $reps; $r++) {
// Alternate which side opens the rep as well.
$order = $r % 2 === 0 ? ['old', 'new'] : ['new', 'old'];
$actual = ['old' => ! $expected, 'new' => ! $expected];
$total = ['old' => 0, 'new' => 0];
for ($c = 0; $c < $chunks; $c++) {
$n = $chunkSize + ($c < $tail ? 1 : 0);
foreach ($order as $which) {
$run = $which === 'old' ? $runOld : $runNew;
$start = hrtime(true);
for ($i = 0; $i < $n; $i++) {
$actual[$which] = $run($uri);
}
$total[$which] += hrtime(true) - $start;
}
}
foreach (['old', 'new'] as $which) {
$repTimes[$which][] = $total[$which] / $iterations / 1000;
// Assertions stay outside the timed chunks so they cannot skew them.
$matchedRoutes[$which] = assertBlock(
$which,
$which === 'old' ? $old : $new,
$actual[$which],
$expected,
$expectedKey,
$table,
$match,
);
}
}
if ($matchedRoutes['old'] !== $matchedRoutes['new']) {
throw new RuntimeException(sprintf(
'Implementations disagree for %s/%s: old=%s, new=%s',
$table, $match,
var_export($matchedRoutes['old'], true),
var_export($matchedRoutes['new'], true),
));
}
$oldBlock = summarize($repTimes['old'], $matchedRoutes['old']);
$newBlock = summarize($repTimes['new'], $matchedRoutes['new']);
$deltaUs = $newBlock['per_op_us'] - $oldBlock['per_op_us'];
$deltaPct = $oldBlock['per_op_us'] === 0.0
? 0.0
: $deltaUs / $oldBlock['per_op_us'] * 100.0;
return [
'php' => PHP_VERSION, 'table' => $table, 'match' => $match,
'count' => $count, 'iterations' => $iterations, 'reps' => $reps,
'expected_match' => $expected, 'uri' => $uri,
'old' => $oldBlock, 'new' => $newBlock,
'delta_us' => $deltaUs, 'delta_pct' => $deltaPct,
'speedup' => $newBlock['per_op_us'] > 0 ? $oldBlock['per_op_us'] / $newBlock['per_op_us'] : 0.0,
'routes_total' => $routesTotal,
];
}Baseline class wiring (the body itself is copied verbatim, 134 lines, from develop@bdf459d2; verified byte-identical with the merge-base):
/**
* checkRoutes() copied verbatim from `develop` @ bdf459d2 (copied 2026-11-16),
* including its comments and its `preg_match(...)` without `!== 1`.
*
* Frozen reference implementation, not framework code: do not edit.
*/
class BenchBaselineRouter extends Router
{
protected function checkRoutes(string $uri): bool
{
$routes = $this->collection->getRoutes($this->collection->getHTTPVerb());
if ($routes === []) {
return false;
}
$uri = $uri === '/' ? $uri : trim($uri, '/ ');
foreach ($routes as $routeKey => $handler) {
$routeKey = $routeKey === '/' ? $routeKey : ltrim((string) $routeKey, '/ ');
$matchedKey = $routeKey;
if (str_contains($routeKey, '{locale}')) {
$routeKey = str_replace('{locale}', '[^/]+', $routeKey);
}
if (preg_match('#^' . $routeKey . '$#u', $uri, $matches)) {
// ... unchanged develop body: locale, redirects, closures,
// setRequest(), setMatchedRoute() ...
return true;
}
}
return false;
}
}
// The "new" side is the branch itself: checkRoutes() is extracted from the
// checked-out system/Router/Router.php and instantiated as a sibling subclass,
// so both sides have the same class shape (a one-method subclass). A standalone
// `new Router()` measured 7-9% faster than a one-method subclass purely because
// of the class shape, which would have been reported as a fake PR win.
$currentBody = checkRoutesMethodSource($root . '/system/Router/Router.php');
eval('class BenchCurrentRouter extends \\CodeIgniter\\Router\\Router {' . $currentBody . '}');Alternative strategies measured (build + match per request, PHP 8.2)
Same 100-route tables; build cost is what a per-request index would pay in production.
| strategy | static last | prefix last | mixed none | dynamic last | dynamic none |
|---|---|---|---|---|---|
| current (regex loop) | 12.24 | 12.03 | 13.26 | 13.58 | 13.82 |
this PR (strpbrk) |
12.30 | 13.41 | 19.22 | 27.85 | 27.76 |
| precomputed flags | 15.30 | 16.79 | 21.70 | 28.27 | 28.27 |
| exact hash + precedence | 15.43 | 15.88 | 21.27 | 28.74 | 28.83 |
| first-segment buckets | 10.70 | 13.46 | 12.53 | 14.00 | 14.00 |
| combined alternation regex | 1.93 | 2.05 | 2.29 | 16.91 | 2.73 |
strpbrk is a regression in every real case; the only strategy with a positive per-request balance is a compiled matcher (one alternation, pattern string assembled once — warm PCRE cache 1.3–2.3 µs, cold compile 114–362 µs if the pattern string changes). It still loses on a late dynamic match (+16%) because the index must then be resolved by re-scanning; capture-group resolution would remove that.
What I suggest
The fast path as written should not be merged: it makes the case it targets barely faster and makes mixed/dynamic routing measurably slower. If router performance is worth pursuing, the direction with actual headroom is a compiled matcher built once per request in getRoutes() (or cached in writable/cache), not a per-key metacharacter scan in the hot loop.
Notes: the branch is not rebased on develop (it is missing 6ad9858 / #10762); that does not affect these tables but should be rebased before merge. The benchmark script lives at benchmarks/bench_router.php.

Description
In
Router::checkRoutes(), every registered route was unconditionally evaluated withpreg_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:
strpbrk($routeKey, "()[]?*+{}^$\.|#")to detect PCRE metacharacters (including the pattern delimiter#).$routeKey !== $uriand skips PCRE execution.$routeKey === $uri, initializes$matches = [$uri]and proceeds directly to dispatch.Benchmark (10,000 iterations per scenario)
Checklist: