Middle
How would you fix a memory leak in your code?
sobes.tech AI
Answer from AI
Would identify the source of the leak using browser developer tools (Timeline / Performance, Memory).
Common causes of memory leaks:
- Dangling object references:
- Forgotten timers (
setInterval,setTimeout) referencing objects. - Undetached event handlers (
removeEventListener). - Closures holding external variables longer than necessary.
- DOM elements removed from the document but still referenced in JavaScript.
- Forgotten timers (
// Example of a leak due to a forgotten timer
const leakyObject = {
data: 'some data'
};
setInterval(() => {
console.log(leakyObject.data); // leakyObject cannot be garbage collected
}, 1000);
- Large data structures:
- Creating and storing excessively large arrays or objects when iterators or streaming could suffice.
- Incorrect cache usage:
- Caches that grow infinitely without eviction strategies (LRU, LFU, etc.).
- Leaks from third-party libraries:
- Check the documentation or source code of libraries for potential issues.
Fixes:
- Cancel events and timers: Ensure all event handlers are detached and timers cleared when destroying a component or object.
// Proper timer cleanup
const leakyObject = {
data: 'some data'
};
let timerId;
function startTimer() {
timerId = setInterval(() => {
console.log(leakyObject.data);
}, 1000);
}
function stopTimer() {
clearInterval(timerId); // Clear the timer
}
- Nullify references: Explicitly nullify references to large or unused objects so the garbage collector can reclaim them.
- Use
WeakMapandWeakSet: To store references to objects that can be garbage collected when no other strong references exist. - Optimize data structures: Use more efficient data structures or approaches (e.g., lazy loading).
- Limit cache size: Implement eviction strategies for caches.
- Update or replace libraries: If the issue is in a third-party library, update it or find an alternative.
After fixing, use developer tools again to confirm the leak is resolved.