Performance: Middleware vs decorator pattern
This concept affects how requests are processed and how code execution impacts response time and resource usage in Node.js applications.
app.use(async (req, res, next) => { await lightAsyncTask(); next(); }); app.use(async (req, res, next) => { await anotherLightAsyncTask(); next(); });
app.use((req, res, next) => { heavySyncTask(); next(); }); app.use((req, res, next) => { anotherHeavySyncTask(); next(); });| Pattern | Event Loop Blocking | CPU Usage | Throughput Impact | Verdict |
|---|---|---|---|---|
| Synchronous middleware with heavy tasks | High | High | Low throughput due to blocking | [X] Bad |
| Asynchronous middleware with light tasks | Low | Low | High throughput, responsive | [OK] Good |
| Synchronous decorator wrapping heavy function | High | High | Blocks event loop during calls | [X] Bad |
| Async decorator wrapping lightweight async function | Low | Low | Non-blocking, smooth execution | [OK] Good |
function logDecorator(fn) {
return function(...args) {
console.log('Calling function');
return fn(...args);
};
}
function greet(name) {
return `Hello, ${name}!`;
}
const decoratedGreet = logDecorator(greet);
console.log(decoratedGreet('Alice'));function logger(req, res, next) {
console.log('Request URL:', req.url);
next;
}function fetchData(userId) {
return `Data for user ${userId}`;
}Pass the test and this pattern moves unknown