问题
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 XMLHttpRequest
object. 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