perf: cache accepts instance on request object#7008
perf: cache accepts instance on request object#7008jonathan-fulton wants to merge 2 commits intoexpressjs:masterfrom
Conversation
Cache the accepts instance using a Symbol to avoid creating a new instance on every call to req.accepts(), req.acceptsEncodings(), req.acceptsCharsets(), and req.acceptsLanguages(). This reduces overhead when multiple accepts methods are called within the same request lifecycle. Fixes expressjs#5906
|
Also, if you’re going to submit PRs that claim performance improvements, please share what improvements you actually observed and include tests. Just because an issue says something could be done doesn’t mean it will result in real improvements. |
Adds a benchmark to measure the performance impact of caching the accepts instance on the request object. Tests both raw instantiation overhead and end-to-end request scenarios.
Benchmark Results@bjohansebas Thanks for the feedback. Here are the benchmark results: Environment
Benchmark ScriptI created a benchmark that compares the performance before (fresh Results
AnalysisWhat we're measuring:
Honest AssessmentThe caching does provide a measurable benefit for instantiation (avoiding
Why This Change Still Has Value
Reproducecd /path/to/express
npm install
node benchmark-accepts.jsHappy to discuss or adjust the approach if needed! |
Summary
The current implementation creates a new
acceptsinstance for each call toreq.accepts(),req.acceptsEncodings(),req.acceptsCharsets(), andreq.acceptsLanguages(). This leads to redundant object creation and header parsing overhead when these methods are called multiple times within the same request lifecycle.Solution
Cache the
acceptsinstance on the request object using a Symbol to avoid property name collisions. The cached instance is reused for all subsequentaccepts*method calls on the same request.Changes
getAccepts()helper function that creates/returns cached instanceaccepts*methods to use the cached instancePerformance
This eliminates N-1 redundant
accepts()instantiations and header parses when Naccepts*methods are called on the same request.Fixes #5906