Performance: Routing patterns
Routing patterns affect how quickly a web app can respond to URL changes and serve the right content, impacting page load and interaction speed.
import { serve } from "https://deno.land/std/http/server.ts"; const routes = new Map([ ["/home", () => new Response("Home Page")], ["/about", () => new Response("About Page")], ["/contact", () => new Response("Contact Page")], ]); serve((req) => { const url = new URL(req.url); const handler = routes.get(url.pathname); return handler ? handler() : new Response("Not Found", { status: 404 }); });
import { serve } from "https://deno.land/std/http/server.ts"; serve(async (req) => { const url = new URL(req.url); if (url.pathname === "/home") { return new Response("Home Page"); } else if (url.pathname === "/about") { return new Response("About Page"); } else if (url.pathname === "/contact") { return new Response("Contact Page"); } else { return new Response("Not Found", { status: 404 }); } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple if-else route checks | N/A (server-side) | N/A | N/A | [X] Bad |
| Map-based direct route lookup | N/A (server-side) | N/A | N/A | [OK] Good |
| Manual string parsing for dynamic routes | N/A (server-side) | N/A | N/A | [X] Bad |
| Precompiled pattern matching library | N/A (server-side) | N/A | N/A | [OK] Good |
router.get('/user/:id', (ctx) => {
const id = ctx.params.id;
ctx.response.body = `User ID is ${id}`;
});
// Request URL: /user/42/user/42?router.get('/post/:postId', (ctx) => {
const postId = ctx.request.params.postId;
ctx.response.body = `Post: ${postId}`;
});/product/123/review/456 where 123 is the product ID and 456 is the review ID. Which route pattern correctly captures both IDs as parameters?Pass the test and this pattern moves unknown