Node.js & Libuv•Part 4: Express, Fastify, APIs & Middleware (36 - 50)
Why Fastify achieves significantly higher throughput.
In Simple Words:
- Radix Tree Routing: Uses
find-my-wayfor $O(K)$ route matching where $K$ is route length. - Pre-Compiled JSON Serializer: Uses
fast-json-stringifywhich compiles JSON schemas into optimized C-like string concatenators, bypassing slowJSON.stringify(). - Optimized Object Allocations: Minimizes garbage collection pressure per request.
javascript
// fast-json-stringify example used internally by Fastify:
const fastJson = require('fast-json-stringify');
const stringify = fastJson({
type: 'object',
properties: { id: { type: 'integer' }, name: { type: 'string' } }
});
console.log(stringify({ id: 1, name: 'Alice' })); // 2x faster than JSON.stringify