我为什么要重用XmlHtt prequest对象?我为、对象、XmlHtt、prequest

2023-09-10 15:59:14 作者:如果不爱,请别伤害

据我了解,这是要尽可能地重用XmlHtt prequest对象的最佳实践。不幸的是,我有一个很难理解为什么。看来,试图通过重用XHR对象,你增加code的复杂性,你可能引入的浏览​​器不兼容的。那么,为什么这么多的人推荐一下?

From what I understand, it's a best practice to reuse XmlHttpRequest objects whenever possible. Unfortunately, I'm having a hard time understanding why. It seems that by trying to reuse XHR objects you increase your code complexity and you introduce possible browser incompatibilities. So why do so many people recommend it?

经过一番研究,我能想出可能的解释这个名单:

After some research, I was able to come up with this list of possible explanations:

在创建较少的对象意味着更少的垃圾回收 在重用XHR对象减少了内存泄漏的几率 创建一个新的XHR对象的开销很高 在浏览器能够在通风橱下进行某种形式的网络优化

但我还是有点怀疑。是否有任何这些理由实际上是有效的?如果不是,有什么正当的​​理由?

But I'm still a bit skeptical. Are any of these reasons actually valid? If not, what is a valid reason?

推荐答案

有有关开放的连接数,你可以在任何一个时间的问题一大堆;通常这是强加在一个浏览器级别在所有版本的Internet Explorer(IE6允许2,IE7允许2,IE8允许4),通常这是通过服务器节流所强加的,有时这是由互联网服务提供商的罚款。

There are a whole host of problems relating to the number of open connections you can have at any one time; often this is imposed at a browser level as in all versions of Internet Explorer (IE6 allows 2, IE7 allows 2, IE8 allows 4), often this is imposed by server throttling and sometimes this is imposed by Internet Service Providers.

如果您有大量不同的XmlHtt prequest对象在一个脚本中,出于某种原因,他们的一些连接没有正确关闭或尚未GC'd,你可能会遇到困难,打开新的连接和完全不知道是怎么回事错了。

If you have a large number of distinct XmlHttpRequest objects in one script, and for some reason some of their connections have not closed properly or have not been GC'd, you may run into difficulty opening new connections and have absolutely no idea what is going wrong.

这和所有你提到的原因。

That and all of the reasons you mention.