diff --git a/StaticRouter.php b/StaticRouter.php new file mode 100644 index 0000000..30610f5 --- /dev/null +++ b/StaticRouter.php @@ -0,0 +1,42 @@ +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; + } +} diff --git a/tests/static.php b/tests/static.php new file mode 100644 index 0000000..83948b9 --- /dev/null +++ b/tests/static.php @@ -0,0 +1,44 @@ +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; +}