Problem Statement
Explain debouncing, throttling, and memoization. When would you use each? Provide implementation and real-world examples.
Explanation
Debouncing, throttling, and memoization are three critical optimization techniques that solve different performance problems.
Debouncing:
Delays function execution until after events stop firing. Resets timer on each event. Function only executes after specified quiet period. Perfect for search inputs, form validation, window resize. Reduces API calls dramatically. Implementation uses setTimeout and clearTimeout.
Throttling:
Limits function execution to once per time interval. Guarantees function runs at regular intervals. Does not wait for quiet period like debounce. Perfect for scroll events, mouse movement, animations, infinite scroll. Ensures consistent execution rate. Implementation uses timestamp or flag checking.
Memoization:
Caches function results based on inputs. Returns cached value for repeated calls with same arguments. Only works with pure functions. Perfect for expensive calculations, recursive algorithms, API calls. Trades memory for speed. Implementation uses Map or object as cache.
Key differences:
Debounce waits for pause in events. Throttle limits frequency during continuous events. Memoization caches results, not execution timing. Debounce may never execute if events keep firing. Throttle guarantees execution. Memoization guarantees same output for same input.
When to use debouncing:
Search autocomplete, wait for user to stop typing. Form field validation after user finishes. Window resize handlers. Autosave after editing stops. Any scenario where you want to wait for user to finish action.
When to use throttling:
Scroll event handlers updating UI. Mouse position tracking. Animation frame limiting. Infinite scroll loading. Button click rate limiting. Any scenario where you need regular updates during continuous events.
When to use memoization:
Expensive calculations called repeatedly. Recursive algorithms like Fibonacci. Complex data transformations. API calls with same parameters. Pure function results. Any scenario where calculation is expensive and repeated.
Implementation considerations:
Debounce and throttle need cleanup. Memoization needs memory management. Consider cache size limits. Use WeakMap for object keys when appropriate. Clear caches periodically if needed.
Real-world performance impact:
Debouncing search can reduce API calls from hundreds to one. Throttling scroll can reduce handler calls from thousands to tens. Memoization can turn O(2^n) Fibonacci into O(n). Proper use can make applications 10-100x more performant.
All three techniques are fundamental to building performant web applications and frequently appear in technical interviews.