写了一个简单的测试用例来重复添加/删除DOM中的100个图像:
<!DOCTYPE html>
<html>
<head><meta http-equiv="X-UA-Compatible" content="IE=edge"/></head>
<body>
<div id="the-place"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var Person = function (firstName, lastName, loginId)
{
this.firstName = firstName;
this.lastName = lastName;
this.loginId = loginId;
this.fullName = this.firstName + " " + this.lastName;
};
var firstNames = [
"George",
"Sandra",
"Billy",
"David",
"Jason"
];
var lastNames = [
"Clark",
"Smith",
"Doe",
"Randall",
"Crank"
];
var loginIds = ["gclark", "ssmith", "bdoe", "drandall", "jcrank"];
var unPopulateAndRepopulateDom = function ()
{
var thePlaceNode = document.getElementById("the-place");
while (thePlaceNode.firstChild) {
thePlaceNode.removeChild(thePlaceNode.firstChild);
}
for (var i=0; i<100; i++)
{
var person = new Person (
firstNames[Math.floor (Math.random ()*firstNames.length)],
lastNames[Math.floor (Math.random ()*lastNames.length)],
loginIds[Math.floor (Math.random ()*loginIds.length)]
);
thePlaceNode.insertAdjacentHTML ( 'beforeend',
'<div>' +
'First Name: <span id="first-name-' + i + '">' +
person.firstName + '</span><br>' +
'Last Name: <span id="last-name-' + i + '">' + person.lastName +
'</span><br>' +
'<img src="acc_icons.png"/>' +
'Full Name: <span id="full-name-' + i + '">' + person.fullName +
'</span><br><br>' +
'</div>'
);
person = null;
}
}
var count = 0;
var startItUp = function ()
{
count++;
unPopulateAndRepopulateDom ();
if (count > 1000)
{
setTimeout (startItUp, 10000); // Finally take a breather for 10
seconds
count = 0;
}
else
setTimeout (startItUp, 1);
}
startItUp ();
});
</script>
</body>
</html>
监视Windows任务管理器中的firefox.exe进程,似乎Firefox每次迭代泄漏内存大约1 MB。在从DOM添加/删除图像的1000次迭代之后,我们实施了10秒的暂停,以允许垃圾收集器“赶上”#34;。当然,我们不应该暂停,但我们想看看这是否有所作为,而且它没有(对于FireFox)。这个确切的测试用例在IE 10和Chrome中运行完美(执行8小时后没有内存泄漏)。注意:我的开发盒是四核,16.0 GB的RAM,Windows 7/64位。
有没有人知道为什么会这样?任何建议将不胜感激!
可以在这里找到一个JSFiddle(http://jsfiddle.net/37wZ7/7/)。