Compare commits
4 Commits
44ad5c5512
...
90b8049dc4
Author | SHA1 | Date | |
---|---|---|---|
90b8049dc4 | |||
290fc105e9 | |||
1bff49e3ba | |||
327981e72e |
|
@ -4,6 +4,10 @@ class SegmentRouter implements Router
|
|||
{
|
||||
public array $routes = [];
|
||||
|
||||
/**
|
||||
* Add a route to the router. The route can contain dynamic segments, which are denoted by a colon. They are
|
||||
* inserted into the node tree per segment; if a segment is dynamic, it is stored under the key ':x'.
|
||||
*/
|
||||
public function add(string $method, string $route, callable $handler): Router
|
||||
{
|
||||
// Expand the route into segments and make dynamic segments into a common placeholder
|
||||
|
@ -11,9 +15,13 @@ class SegmentRouter implements Router
|
|||
return str_starts_with($segment, ':') ? ':x' : $segment;
|
||||
}, explode('/', trim($route, '/')));
|
||||
|
||||
// Push each segment into the routes array as a node
|
||||
// Push each segment into the routes array as a node, except if this is the root node
|
||||
$node = &$this->routes;
|
||||
foreach ($segments as $segment) $node = &$node[$segment];
|
||||
foreach ($segments as $segment) {
|
||||
// skip an empty segment, which allows us to register handlers for the root node
|
||||
if ($segment === '') continue;
|
||||
$node = &$node[$segment]; // build the node tree as we go
|
||||
}
|
||||
|
||||
// Add the handler to the last node
|
||||
$node[$method] = $handler;
|
||||
|
@ -21,44 +29,45 @@ class SegmentRouter implements Router
|
|||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup a route in the router. This method will return the handler for the route if it is found, or a 404 or 405
|
||||
* status code if the route is not found or the method is not allowed. If the route contains dynamic segments, the
|
||||
* method will return an array with the handler and the dynamic segments.
|
||||
*
|
||||
* @return [callable, array] | int
|
||||
*/
|
||||
public function lookup(string $method, string $uri): int|array
|
||||
{
|
||||
// Expand the URI into segments
|
||||
$uriSegments = explode('/', trim($uri, '/'));
|
||||
// node is a reference to our current location in the node tree
|
||||
$node = $this->routes;
|
||||
|
||||
// params will hold any dynamic segments we find
|
||||
$params = [];
|
||||
|
||||
// Traverse the routes array to find the handler
|
||||
foreach ($uriSegments as $segment) {
|
||||
// Check if the segment exists in the node
|
||||
// We'll split up the URI into segments and traverse the node tree
|
||||
foreach (explode('/', trim($uri, '/')) as $segment) {
|
||||
// if there is a node for this segment, move to it
|
||||
if (isset($node[$segment])) {
|
||||
$node = $node[$segment];
|
||||
} else {
|
||||
// Handle dynamic segments (starting with ":")
|
||||
$dynamicSegment = null;
|
||||
|
||||
// Loop through the node and find the first dynamic segment
|
||||
foreach ($node as $k => $v) {
|
||||
if (str_starts_with($k, ':')) {
|
||||
$dynamicSegment = $k;
|
||||
break; // Break early as we only need one match
|
||||
}
|
||||
}
|
||||
|
||||
// If no dynamic segment was found, return 404
|
||||
if ($dynamicSegment === null) return 404;
|
||||
|
||||
// Otherwise, store the parameter and move to the dynamic node
|
||||
$params[] = $segment;
|
||||
$node = $node[$dynamicSegment];
|
||||
continue;
|
||||
}
|
||||
|
||||
// if there is a dynamic segment, move to it and store the value
|
||||
if (isset($node[':x'])) {
|
||||
$params[] = $segment;
|
||||
$node = $node[':x'];
|
||||
continue;
|
||||
}
|
||||
|
||||
// if we can't find a node for this segment, return 404
|
||||
return 404;
|
||||
}
|
||||
|
||||
// Check if the HTTP method is supported
|
||||
// if we fail to find a handler for the method, return 405
|
||||
if (!isset($node[$method])) return 405;
|
||||
|
||||
// Return the handler and parameters
|
||||
return [$node[$method] , $params];
|
||||
// return the handler and any dynamic segments we found
|
||||
return [$node[$method], $params];
|
||||
}
|
||||
|
||||
|
||||
|
|
42
StaticRouter.php
Normal file
42
StaticRouter.php
Normal file
|
@ -0,0 +1,42 @@
|
|||
<?php
|
||||
|
||||
class StaticRouter
|
||||
{
|
||||
public static $routes = [];
|
||||
|
||||
public static function add(string $method, string $route, callable $handler): void
|
||||
{
|
||||
$segments = array_map(function($segment) {
|
||||
return str_starts_with($segment, ':') ? ':x' : $segment;
|
||||
}, explode('/', trim($route, '/')));
|
||||
|
||||
$node = &self::$routes;
|
||||
foreach ($segments as $segment) {
|
||||
if ($segment === '') continue;
|
||||
$node = &$node[$segment];
|
||||
}
|
||||
|
||||
$node[$method] = $handler;
|
||||
}
|
||||
|
||||
public static function lookup(array $node /* = &$this->routes */, string $method, string $uri): int|array
|
||||
{
|
||||
$uriSegments = explode('/', trim($uri, '/'));
|
||||
$params = [];
|
||||
|
||||
if (isset($node[$method])) return [$node[$method], $params];
|
||||
|
||||
if (! $node2 = array_reduce($uriSegments, function ($carry, $segment) use (&$params) {
|
||||
if (isset($carry[$segment])) return $carry[$segment];
|
||||
if (isset($carry[':x'])) {
|
||||
$params[] = $segment;
|
||||
return $carry[':x'];
|
||||
}
|
||||
return null;
|
||||
}, $node)) return 404;
|
||||
|
||||
if (isset($node2[$method])) return [$node2[$method], $params];
|
||||
|
||||
return 405;
|
||||
}
|
||||
}
|
|
@ -8,11 +8,6 @@
|
|||
The requests are randomly picked from the array of routes.
|
||||
*/
|
||||
|
||||
// if there's a flag, reset the opcache
|
||||
if (in_array('-f', $argv)) {
|
||||
opcache_reset();
|
||||
}
|
||||
|
||||
require_once 'tools.php';
|
||||
|
||||
$r = new SegmentRouter();
|
||||
|
@ -20,7 +15,8 @@ $r = new SegmentRouter();
|
|||
// Blog lookups
|
||||
$blog = readAndAddRoutes('blog.txt', $r);
|
||||
writeRoutesToFile($r->routes, 'storage/segment/blog.txt');
|
||||
echoTitle("Starting github lookups");
|
||||
echoTitle("Starting blog lookups");
|
||||
runIterations(10000, $r, $blog);
|
||||
runIterations(100000, $r, $blog);
|
||||
runIterations(1000000, $r, $blog);
|
||||
unset($blog);
|
||||
|
|
|
@ -8,11 +8,6 @@
|
|||
The requests are randomly picked from the array of routes.
|
||||
*/
|
||||
|
||||
// if there's a flag, reset the opcache
|
||||
if (in_array('-f', $argv)) {
|
||||
opcache_reset();
|
||||
}
|
||||
|
||||
require_once 'tools.php';
|
||||
require_once __DIR__ . '/../SimpleRouter.php';
|
||||
|
||||
|
|
44
tests/static.php
Normal file
44
tests/static.php
Normal file
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
require_once 'tools.php';
|
||||
require_once __DIR__ . '/../StaticRouter.php';
|
||||
|
||||
$r = new SegmentRouter();
|
||||
|
||||
// Big test
|
||||
$big = readRoutes('big.txt');
|
||||
foreach ($big as $route) {
|
||||
[$method, $path] = $route;
|
||||
$r->add($method, $path, function() {
|
||||
return true;
|
||||
});
|
||||
}
|
||||
echoTitle("Starting big lookups");
|
||||
|
||||
$start = microtime(true);
|
||||
$reqs = 0;
|
||||
for ($i = 0; $i < 1000000; $i++) {
|
||||
$index = array_rand($big);
|
||||
[$method, $path] = $big[$index];
|
||||
$rstart = microtime(true);
|
||||
$res = StaticRouter::lookup($r->routes, $method, $path);
|
||||
if ($res === 404 || $res === 405) {
|
||||
die("404 or 405\n");
|
||||
}
|
||||
$reqs += microtime(true) - $rstart;
|
||||
}
|
||||
echo "Time: " . Color::cyan(number_format(microtime(true) - $start, 10) . " s\n");
|
||||
echo "Peak memory: " . Color::magenta(round(memory_get_peak_usage() / 1024, 1) . " kb\n");
|
||||
echo "Avg/lookup: " . Color::yellow(number_format($reqs / 1000000, 10) . " s\n");
|
||||
|
||||
function readRoutes(string $file): array
|
||||
{
|
||||
$array = [];
|
||||
$routes = file($file);
|
||||
foreach ($routes as $route) {
|
||||
[$method, $path] = explode(' ', $route);
|
||||
$path = trim($path);
|
||||
$array[] = [$method, $path];
|
||||
}
|
||||
return $array;
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
/
|
||||
├── /
|
||||
│ └── GET
|
||||
├── GET
|
||||
├── :x
|
||||
│ └── GET
|
||||
├── tags
|
||||
|
|
|
@ -1,5 +1,11 @@
|
|||
<?php
|
||||
|
||||
// if there's a flag, reset the opcache
|
||||
if (in_array('-f', $argv)) {
|
||||
opcache_reset();
|
||||
echoTitle("opcache reset");
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/../Router.php';
|
||||
require_once __DIR__ . '/../SegmentRouter.php';
|
||||
require_once __DIR__ . '/../TrieRouter.php';
|
||||
|
@ -101,29 +107,67 @@ function readAndAddRoutes(string $file, Router &$r): array
|
|||
}
|
||||
|
||||
function runIterations(int $iterations, $r, array $routes) {
|
||||
echo "Running $iterations iterations\n";
|
||||
$start = microtime(true);
|
||||
$interval = $iterations / 10;
|
||||
echo "\n🚀 Running $iterations iterations...\n";
|
||||
|
||||
$start = microtime(true); // start the timer
|
||||
$reqs = 0; // track the timing of lookups
|
||||
$longest = 0; // track the longest lookup time
|
||||
$shortest = 0; // track the shortest lookup time
|
||||
$longestRoute = '';
|
||||
$shortestRoute = '';
|
||||
|
||||
for ($i = 0; $i < $iterations; $i++) {
|
||||
// pick a random route from the array
|
||||
[$method, $path] = $routes[array_rand($routes)];
|
||||
|
||||
// replace all :params/ with random values
|
||||
$uri = preg_replace_callback('/:(\w+)/', function($matches) {
|
||||
return rand(1, 100);
|
||||
}, $path);
|
||||
$start2 = microtime(true);
|
||||
$res = $r->lookup($method, $uri);
|
||||
|
||||
$start2 = microtime(true); // start the timer for the lookup
|
||||
|
||||
$res = $r->lookup($method, $uri); // run the lookup
|
||||
|
||||
$reqs += microtime(true) - $start2; // add this lookup time
|
||||
if ($shortest == 0 || microtime(true) - $start2 < $shortest) {
|
||||
$shortest = microtime(true) - $start2; // track the shortest lookup time
|
||||
$shortestRoute = "$method $uri";
|
||||
}
|
||||
if (microtime(true) - $start2 > $longest) {
|
||||
$longest = microtime(true) - $start2; // track the longest lookup time
|
||||
$longestRoute = "$method $uri";
|
||||
}
|
||||
|
||||
// if any error was encountered, print it and exit
|
||||
if ($res === 404 || $res === 405) {
|
||||
echo Color::red("Failed to handle request.\n$method $res\n"."├─ URI: $uri\n└─ Path: $path\n");
|
||||
echo Color::yellow("Completed $i iterations before failure.\n");
|
||||
exit(1);
|
||||
}
|
||||
if ($i !== 0 && $i % ($interval) === 0) echoMemoryAndTime($i, $start2);
|
||||
}
|
||||
echo Color::blue("✔️ Done!")."\n";
|
||||
|
||||
// echo peak memory usage
|
||||
echo "Peak memory: " . Color::magenta(round(memory_get_peak_usage() / 1024, 1) . " kb\n");
|
||||
|
||||
// total time used for this run
|
||||
echo "Time: " . Color::cyan(number_format(microtime(true) - $start, 10) . " s\n");
|
||||
|
||||
// echo the average time per request
|
||||
echo "Avg/lookup: " . Color::yellow(number_format((microtime(true) - $start) / $iterations, 10) . " s\n");
|
||||
echo "\n";
|
||||
echo "Avg/lookup: " . Color::yellow(number_format($reqs / $iterations, 10) . " s\n");
|
||||
|
||||
// echo the shortest lookup time
|
||||
echo "Shortest lookup: " . Color::green(number_format($shortest, 10) . " s\n");
|
||||
|
||||
// echo the longest lookup time
|
||||
echo "Longest lookup: " . Color::red(number_format($longest, 10) . " s\n");
|
||||
|
||||
echo Color::black("==============================================") . "\n";
|
||||
|
||||
// echo the longest and shortest routes
|
||||
echo "Shortest route: " . Color::green($shortestRoute) . "\n";
|
||||
echo "Longest route: " . Color::red($longestRoute) . "\n";
|
||||
}
|
||||
|
||||
// take a route tree (array) and store it in a file to be read
|
||||
|
|
|
@ -8,11 +8,6 @@
|
|||
The requests are randomly picked from the array of routes.
|
||||
*/
|
||||
|
||||
// if there's a flag, reset the opcache
|
||||
if (in_array('-f', $argv)) {
|
||||
opcache_reset();
|
||||
}
|
||||
|
||||
require_once 'tools.php';
|
||||
|
||||
$r = new TrieRouter();
|
||||
|
|
Loading…
Reference in New Issue
Block a user