Reusing XMTHttpRequest object?

痞子三分冷 提交于 2021-02-19 05:53:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/27888471/reusing-xmthttprequest-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!