重用XMTHttpRequest对象? [英] Reusing XMTHttpRequest object?
问题描述
我正在尝试重写一些Ajax代码,以使其更适合自动完成需求.在这种情况下,有时您必须中止先前的请求 xhr.abort()
,因此重用该 XMLHttpRequest
对象(我简称为xhr
此处).
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).
我试图了解重用 XMLHttpRequest
对象是个好主意.您会看到哪些利弊?
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:此重写将使用本机ES6样式的Promise,因此只能在较新的Web浏览器中运行.
PS: This rewrite will use native ES6-style Promise so it can only run in newer web browsers.
推荐答案
就像@Bergi所建议的计时测试一样:
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();
在Chrome中,这里的结果是:
The result here, in Chrome, is:
test-xhr-reuse.js:6 XHR finished loading: GET ...
reuse: 510.000ms
new: 386.000ms
所以...在慢速的PC上每次通话0.1毫秒,这不值得麻烦...
So... 0.1 ms per call on a slow pc, it is not worth the trouble...
现在等待-重用xhr甚至更慢...不值得.;-)
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.
这篇关于重用XMTHttpRequest对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!