views:

296

answers:

1

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:

  1. Fewer objects created means less garbage collection
  2. Reusing XHR objects reduces the chance of memory leaks
  3. The overhead of creating a new XHR object is high
  4. The browser is able to perform some sort of network optimization under hood

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

+4  A: 

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.

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.

Finbarr