Agile Ajax

Object Pooling and Reusing XMLHttpRequest in IE

Thousands of XMLHttpRequest objects are needlessly being killed every second of every day. Cruel web developers are thoughtlessly creating new XHR objects, even though they can now be reused in every browser, including IE. As a public service, I thought I'd show one approach for pooling XHR objects, and saving memory and CPU time.

All kidding aside, pooling reusable objects is easy and can save a great deal of processing time, especially in IE. Here is my example XHR pool. It relies on good programmer behavior, i.e. they need to release any XHR objects using XHRFactory.release().

var XHRFactory = (function(){
// static private member
var stack = new Array();
var poolSize = 10;

var nullFunction = function() {}; // for nuking the onreadystatechange

// private static methods

function createXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject('Microsoft.XMLHTTP')
}
}

// cache a few for use
for (var i = 0; i < poolSize; i++) {
stack.push(createXHR());
}

// shared instance methods
return ({
release:function(xhr){
xhr.onreadystatechange = nullFunction;
stack.push(xhr);
},
getInstance:function(){
if (stack.length < 1) {
return createXHR();
} else {
return stack.pop();
}
},
toString:function(){
return "stack size = " + stack.length;
}
});
})();

You would use this object as follows:

var xhr = XHRFactory.getInstance();
var url = "http://www.xyz.com/someresource/....";
// do the operation
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
// if "OK"
if (xhr.status==200) {
// process the response
}
XHRFactory.release(xhr);
}
};
xhr.send("");

We know from Eric Pascarello and Pava Keely that as long as you perform an open on the XHR object before you set the onreadystatchange, you can reuse the object in IE. Some simple benchmarks shows that allocating 100 XHR objects 500 times sees a performance improvement of over 50% in Firefox and a whopping 93% in IE6.

So, think before you needlessly create those XHR objects. The application you save could be your own.


Technorati : , , ,

Comments: 1 so far

  1. Hi Dietrich,

    Interesting….
    But I thought IE was pooling connections, by default.

    I wrote a test harness that essentially opened 10 async connections to the website it originated from and tried to perform a long running operation. Look at my blog entry here http://www.thinkfarahead.com/2007/09/using-script-to-verify-ie-xmlhttp.html

    But Now, I find that firefox is doing it too!

    Thoughts?

    Regards, Vyas

    Comment by Vyas Bharghava, Monday, September 24, 2007 @ 12:19 pm

Leave a comment

Powered by WP Hashcash

About Pathfinder

  • We design and build extraordinary applications for companies looking to make the next great idea a reality.
  • learn more

Topics

WordPress

Comments about this site: info@pathf.com