Reviewer · Performance Optimization
Minimize allocations in hot paths
In code that runs frequently (per element, per array item, per render, per request), avoid unnecessary allocations, copies, and closures, and order checks so the common/cheap case exits early. Specifically:
In code that runs frequently (per element, per array item, per render, per request), avoid unnecessary allocations, copies, and closures, and order checks so the common/cheap case exits early. Specifically:
- Don’t allocate new objects/arrays or spread existing ones just to iterate or pass data around; mutate or read in place when possible. For example, prefer explicit property access over
{...data, color, node}inside a per-node loop that runs on every render. - Reuse precomputed/cached values (e.g. cached opening-tag chunks) instead of recomputing/re-encoding them when the inputs haven’t changed; only fall back to the slower path when something actually differs.
- Avoid creating closures inside loops or conditionals when a
.bind()or a module-scoped function would do, e.g.defaultEncodeFormAction.bind(reference, identifierPrefix)instead of wrapping it in an arrow function. If a closure is only needed on one branch of a condition, allocate it only on that branch rather than unconditionally. - Prefer built-in, engine-optimized APIs (e.g.
TextDecoder) over manual chunking/looping withFunction.applyor repeatedsubarrayallocations, especially when processing large buffers. - When accumulating strings/arrays repeatedly (e.g. building a header value), guard the concatenation with a cheap check (
if (linkHeader !== '') linkHeader += ', ';) rather than unconditionally concatenating, which can force expensive rope-flattening or cloning. - Put the cheap/likely-to-succeed check before expensive fallback work (e.g. attempt
set.delete(instance)first, and only run a scanning loop if that fails; return early from a lookup when the backing collection is empty). - When refactoring for memory/allocation efficiency, verify with benchmarks that the change is a net win and doesn’t silently change observable behavior (e.g. an “approximate” byte length used where exact length is assumed) — don’t trade correctness or layering guarantees for a marginal or unproven perf gain.
- For data structures/APIs whose size could grow unbounded under load (e.g. per-request caches, dedup tables), impose an explicit, documented size/length limit rather than letting them grow proportionally to input size.
Always back non-trivial performance changes with before/after measurements, and prefer the simplest fix that removes the extra allocation without introducing new correctness risks or untested code paths.</description> </invoke>