The following javascript code seems to leak memory but I’m not sure why. I’ve tried this in chrome 19 and firefox 12. The code is below:
<body>
<input id="add" type="button" value="add" onclick="add()" />
<input id="remove" type="button" value="remove" onclick="remove()" />
<div id="content">
</div>
</body>
<script>
var count = 0;
function add() {
var i = 0,
newdiv;
for (i = 0; i < 10000; i++) {
newdiv = document.createElement('div');
document.getElementById("content").appendChild(newdiv);
newdiv.setAttribute('id', "div" + count);
newdiv.innerHTML = "section " + count;
newdiv = null;
count = count + 1;
}
}
function remove() {
var i = 0;
for (i = 0; i < count; i++) {
document.getElementById("content").removeChild(document.getElementById("div" + i));
}
count = 0;
}
</script>
When you keep clicking the add button and then the remove button the memory in Windows Task Manager keeps increasing. I expected the memory to decrease at some point when garbage collection kicks in but this never seems to happen.
So, my questions are: is there a memory leak in this code? And if so how can I refactor the code to fix the leak?
I have tested this with Chrome 19.0 and yes, you are right, memory increases. But after about 30 Seconds, garbage collection kicks in and it gets back to normal.