2

I am trying to rewrite some ajax code to make it fit better with the needs for autocomplete. In that situation you have to abort a previous request sometimes, xhr.abort(), so it feels rather natural to reuse that XMLHttpRequest object (which I just called xhr here).

I am trying to understand whether it is a good or bad idea to reuse the XMLHttpRequestobject. What pros and cons can you see?

PS: This rewrite will use native ES6-style Promise so it can only run in newer web browsers.

Leo
  • 4,136
  • 6
  • 48
  • 72
  • 1
    I don't think an object pool of xhr objects will help performance a lot (the network is the slow part), but you can still try and compare. – Bergi Jan 11 '15 at 15:16
  • 1
    @Bergi: In this situation I have the xhr object right there and can immediately reuse it. (I have new input for the autocomplete, I mean.) So there is less overhead than usual, i.e. no object pool is required. But, yes, I can time that to see if there is anything to gain at all. :-) – Leo Jan 11 '15 at 15:20
  • I think the more important thing than speed performance here is the **Memory** Leaks or overhead it may impose to create many new XMLHttpRequest object each time! – S.Serpooshan Oct 16 '18 at 09:10

1 Answers1

2

Just a timing test as @Bergi suggested:

function initCache(url) {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url); xhr.send();
    console.log("Initialized cache");
}

function reuseXhr(url, numLoops) {
    var xhr = new XMLHttpRequest();
    for (var i=0; i<numLoops; i++) {
        xhr.open("get", url); xhr.send();
    }
    xhr.abort();
}

function newXhr(url, numLoops) {
    var xhr;
    for (var i=0; i<numLoops; i++) {
        xhr = new XMLHttpRequest();
        xhr.open("get", url); xhr.send(); xhr.abort();
    }
}
function testIt() {
    var url = "http://urlwithcors.com/"; // Pseudo-URL with CORS enabled
    var numLoops = 1000;
    initCache(url);
    setTimeout(function(){
        console.time("reuse"); reuseXhr(url, numLoops); console.timeEnd("reuse");
        console.time("new"); newXhr(url, numLoops); console.timeEnd("new");
    }, 5000);
}
testIt();

The result here, in Chrome, is:

test-xhr-reuse.js:6 XHR finished loading: GET ...
reuse: 510.000ms
new: 386.000ms

So... 0.1 ms per call on a slow pc, it is not worth the trouble...

Now wait - it is even slower to reuse xhr... Not worth it. ;-)

A bit more testing tells there is no difference at all. It is just a matter of chance.

Leo
  • 4,136
  • 6
  • 48
  • 72
  • 1
    You forgot to pass `numLoops` to your function call? – Bergi Jan 11 '15 at 16:13
  • Eh, thanks @Bergi. Corrected. I am definitively not a coder. I never read my code. I just know what it is supposed to do, how it is structured, etc... ;-) – Leo Jan 11 '15 at 18:07