i stuck into memory leak in js problems.
Javascript:
var index = 0;
function leak() {
console.log(index);
index++;
setTimeout(leak, 0);
}
leak();
here is my test codes, and i use instruments.app to detect memory use of it, and the memory is going up very fast.
i am doubt that there seems no variables occupy the memory.
why?
any thought is appreciate.
Hence there is no explicit way to allocate or free up memory in JavaScript. Just initializing objects allocates memory for them. When the variable goes out of scope, it is automatically garbage collected(frees up memory taken by that object.)
Memory management is often neglected by developers due to misconceptions of automatic memory allocation by JavaScript engines, leading to memory leaks and, ultimately, poor performance. In this article, we'll explore memory management, types of memory leaks, and hunting memory leaks in JavaScript using Chrome DevTools.
Your code creates a set of closures. This prevents the release of memory. In your example the memory will be released after the completion of all timeouts.
This can be seen (after 100 seconds):
var index = 0;
var timeout;
function leak() {
index++;
timeout = setTimeout(leak, 0);
}
leak();
setTimeout(function() {
clearTimeout(timeout);
}, 100000);
setInterval(function() {
console.log(process.memoryUsage());
}, 2000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With