i was wondering if the following code would cause some problems like memory leak
<html>
<head>
<script type='text/javascript' src='jquery-1.4.2.js'> </script>
<script type="text/javascript">
function a(){
for(var i = 0; i < 50000; i++){
$("#d").html("<span>" + i + "</span>");
}
}
</script>
</head>
<body onload='a();'>
<div id="d"></div>
</body>
A simple span is being created here in each iteration. The
html()function in jQuery runs an internalcleanDatafunction that removes associated data and events from all contained nodes which isn’t the case here anyways.Then jQuery sets the innerHTML property to the passed in string which frees the existing elements. It’s up to the browser’s garbage collector to reclaim that memory whenever it can. There are no leaks in this code at all. Chrome is actually very fast in releasing that memory. I see a drop off from 2.421MB to 748KB mainly from the span elements being released in under 3 seconds.
It does not wait for the page to unload to release this memory. These three snapshots were spaced apart by less than a second in which time almost 26000
HTMLElementobjects were released from memory.Before opening the page
After opening page (23000 HTMLElement objects had already been released immediately, around 27000 were remaining)
Less than a second later (all 27000 objects except 1 were released)