使用XMLHttpRequest和setInterval进行内存泄漏

问题描述:

以下是我在Google Chrome 19.0.1061.1(官方版本125213)开发的代码:

Here's some code that I run on Google Chrome 19.0.1061.1 (Official Build 125213) dev:

<html>
<title>Memory Leak</title>
<script type="text/javascript">
    (function(){
        this.window.setInterval(function() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '', false);
            xhr.send();
        }, 50);
    }).call(this);
</script>
</html>

当我检查chrome://任务中的内存使用情况时,我可以看到私有内存是无限期成长(8GB RAM配置)。
如果我将上面的代码示例更改为类似的内容:

When I inspect memory usage in chrome://tasks, I can see that "Private Memory" is growing up indefinitely (8GB RAM config). If I change the sample of code above to something like that:

<html>
<title>Memory Leak</title>
<script type="text/javascript">
    (function(){
        var xhr = new XMLHttpRequest();
        var timeout = this.window.setInterval(function() {
            xhr.open('GET', '', false);
            xhr.send();
        }, 50);
    }).call(this);
</script>
</html>

现在好了。

我不喜欢得到它。 为什么保持对setInterval函数的引用有助于为什么只定义一个xhr有助于自上一个声明处于闭包中?它只与v8有关吗?

I don't get it. Why keeping a reference to the setInterval function helps and why defining only one xhr helps since previous declaration was in a closure? Is it related only to v8?

我很感激你对它的见解。

I would appreciate your insights on it.

在第一个中,您将在每次调用迭代器函数时实例化一个新的XMLHttpRequest对象。请求对象将至少存在,直到HTTP请求完成。每秒启动200个HTTP请求会阻塞浏览器,因为它实际上不会执行所有请求;它将打开多少并发连接是有限制的。

In the first one, you're instantiating a new XMLHttpRequest object on each call to the iterator function. The request objects will stick around at least until the HTTP requests complete. Initiating 200 HTTP requests per second is going to clog the browser up something fierce, since it won't actually perform all the requests; there's a limit to how many concurrent connections it'll open.