Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

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

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?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...