Ajax-intensive page: reuse the same XMLHttpRequest object or create new one every time?

吃可爱长大的小学妹 提交于 2019-11-27 06:12:46

问题


I'm working on some sort of online multiuser editor / coop interface, which will be doing a lot (as in, thousands) of ajax requests during one page lifetime.

What would be best: ('best' in terms of stability, compatibility, avoiding trouble)

  1. Create one XMLHttpRequest object and reuse that for every HTTP request

  2. Create a new XMLHttpRequest object for every HTTP request

  3. Manage a dynamic 'pool' of XMLHttpRequest objects, creating a new one when starting a HTTP request and no existing object is available, and tagging a previously created object as 'available' when its last request was completed successfully

I think 1 is not an option, cause some requests may fail, I may be initiating new requests while a previous one is not finished yet, etc.

As for 2, I guess this is a memory leak, or may result in insane memory/resource usage. Or can I somehow close or delete an object when its request is finished? (where/how?) Or does the JS garbage collector properly take care of this itself?

Never tried 3 before but it feels like the best of both worlds. Or is an approach like that unnecessary, or am I still missing potential problems? Exactly when can I assume a request to be finished (thus, the object being available for a new request), is that when receiving readyState 4 and http status 200 ? (i.e. can I be sure no more updates or callbacks will ever follow after that?)


回答1:


Create a new one when you need one. The GC will deal with the old ones once they are not needed anymore.

However, for something like a cooperative editor you might want to consider using WebSockets instead of sending requests all the time. The overhead of a small HTTP request is huge while there is almost no overhead with a WebSocket connection.



来源:https://stackoverflow.com/questions/11079543/ajax-intensive-page-reuse-the-same-xmlhttprequest-object-or-create-new-one-ever

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