Why RadixRouter Beats Other PHP Routers in Speed and Memory
RadixRouter offers O(k) dynamic routing with support for optional segments, wildcards, and static hash‑based routes, provides a simple installation via Composer, includes usage examples, caching strategies, and benchmark results showing it outperforms FastRoute and SymfonyRouter in both registration time and lookup speed while using less memory.
Overview
RadixRouter is a high‑performance PHP router that matches routes in O(k) time, where k is the number of path segments. It supports required, optional, and wildcard parameters, and stores static routes in a hash map for fast exact matching with minimal memory.
Installation
Install via Composer: composer require wilaak/radix-router Or include the class file directly: require '/path/to/RadixRouter.php'; Requires PHP 8.0 or higher (tests run on PHP 8.3).
Basic Usage
Typical usage in a PHP‑FPM environment:
use Wilaak\Http\RadixRouter;
$router = new RadixRouter();
$router->add('GET', '/:world?', function ($world = 'World') {
echo "Hello, $world!";
});
$method = strtoupper($_SERVER['REQUEST_METHOD']);
$path = rawurldecode(strtok($_SERVER['REQUEST_URI'], '?'));
$result = $router->lookup($method, $path);
switch ($result['code']) {
case 200:
$result['handler'](...$result['params']);
break;
case 404:
http_response_code(404);
echo '404 Not Found';
break;
case 405:
header('Allow: ' . implode(', ', $result['allowed_methods']));
http_response_code(405);
echo '405 Method Not Allowed';
break;
}Registering Routes
Use add() to register routes. Handlers can be any callable. Matching order is static routes first, then parameter routes. Trailing slashes are ignored.
// Static route
$router->add('GET', '/about', 'handler');
// Multiple methods
$router->add(['GET', 'POST'], '/form', 'handler');
// Required parameter
$router->add('GET', '/users/:id', 'handler');
// Optional parameter (must be last segment)
$router->add('GET', '/hello/:name?', 'handler');
// Multiple optional parameters (must be at the end)
$router->add('GET', '/archive/:year?/:month?', 'handler');
// Wildcard parameter (last segment only)
$router->add('GET', '/files/:path*', 'handler');Route Caching
Rebuilding the routing tree on every request adds overhead. A simple cache stores the router tree and static routes in a PHP file, allowing OPcache to serve it with near‑zero startup cost. Anonymous functions cannot be cached because they are not serializable; only handlers representable as strings, arrays, or serializable objects should be cached. Ensure atomic writes to avoid race conditions.
$cacheFile = __DIR__ . '/routes.cache.php';
if (!file_exists($cacheFile)) {
// Build routes
$router->add('GET', '/', 'handler');
$routes = [
'tree' => $router->tree,
'static' => $router->static,
];
file_put_contents($cacheFile, '<?php return ' . var_export($routes, true) . ';');
} else {
$routes = require $cacheFile;
$router->tree = $routes['tree'];
$router->static = $routes['static'];
}HEAD Request Support
According to the HTTP specification, any route handling GET should also support HEAD. RadixRouter does not add this automatically; in custom server environments you must ensure that HEAD responses contain no body.
Performance
RadixRouter is among the fastest pure‑PHP routers for dynamic segments. Benchmark results (single‑thread, Xeon E‑2136, PHP 8.4.8 CLI, OPcache enabled) show:
Simple app (33 routes) : registration 0.04 ms, lookup 3,233,227 req/s, memory 375 KB (peak 456 KB).
Avatax API (256 routes) : registration 0.25 ms, lookup 2,127,808 req/s, memory 587 KB (peak 588 KB).
Bitbucket API (178 routes) : registration 0.17 ms, lookup 1,781,226 req/s, memory 532 KB (peak 533 KB).
In each case RadixRouter outperforms FastRoute and SymfonyRouter in registration speed, lookup throughput, and memory usage.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
