Reviewer · Algorithms
Avoid quadratic or unbounded recursion
Watch for hidden superlinear cost and unbounded recursion when processing collections, chains, or listener lists that can grow large or deep at runtime.
Watch for hidden superlinear cost and unbounded recursion when processing collections, chains, or listener lists that can grow large or deep at runtime.
- Detect quadratic blowup: re-scanning or re-merging an entire accumulated structure (e.g. a Set or array) on every update turns an O(n) workload into O(n²). Instead, track only the delta since the last pass (e.g. a cursor/pointer per consumer, or a per-source “last seen” index) and merge just the new entries.
- Pick data structures that match the access pattern: if you need to remove from the front of a buffer repeatedly, avoid
Array.shift()/splice()(O(n) per call); use an index cursor into the array or a linked list so removal/advance is O(1) and you never pay for a memory copy. - Avoid recursion for operations whose depth is driven by user/data input (long promise chains, long “previous”/”awaited” links, many listeners on the same chunk). Recursive calls on such structures can stack-overflow in production. Convert these to iterative loops, or restructure the recursive call into a “check state, then act” pattern instead of calling back into the same function:
// Avoid: recursing back into the same function for every listener
function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) {
// ...fulfill listeners...
// status may have changed — don't recurse, just continue:
if (chunk.status === INITIALIZED) {
wakeChunk(resolveListeners, chunk.value);
} else if (chunk.status === ERRORED) {
rejectChunk(rejectListeners, chunk.reason);
}
}
- Before adding an extra traversal/allocation step (e.g. flattening a tree into an array purely to diff two trees), consider whether a single combined traversal (e.g. simultaneous DFS over both trees) achieves the same result with less memory churn and fewer passes.
When implementing or reviewing such logic, reason explicitly about worst-case complexity and recursion depth relative to expected input size, and add a regression test (e.g. counting operations across many iterations) to catch complexity regressions.</description> </invoke>