問題描述
我正在開發某種在線多用戶編輯器/合作界面,它將在一個頁面的生命周期內執行大量(如數千個)ajax 請求.
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)
創建一個 XMLHttpRequest 對象并為每個 HTTP 請求重用它
Create one XMLHttpRequest object and reuse that for every HTTP request
為每個 HTTP 請求創建一個新的 XMLHttpRequest 對象
Create a new XMLHttpRequest object for every HTTP request
管理 XMLHttpRequest 對象的動態池",在啟動 HTTP 請求且沒有現有對象可用時創建一個新對象,并在上次請求成功完成時將先前創建的對象標記為可用"
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
我認為 1 不是一個選項,因為某些請求可能會失敗,我可能會在前一個請求尚未完成時發起新請求,等等.
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.
至于 2,我猜這是內存泄漏,或者可能導致瘋狂的內存/資源使用.或者我可以在請求完成時以某種方式關閉或刪除對象嗎?(在哪里/如何?)或者 JS 垃圾收集器本身是否妥善處理這個問題?
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?
以前從未嘗試過 3,但感覺就像兩全其美.或者這樣的方法是不必要的,還是我仍然錯過了潛在的問題?究竟什么時候可以假設請求完成(因此,該對象可用于新請求),是在接收 readyState 4 和 http status 200 時?(即,我可以確定在那之后不會再有更新或回調嗎?)
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?)
推薦答案
當你需要的時候創建一個新的.一旦不再需要舊的,GC 將處理它們.
Create a new one when you need one. The GC will deal with the old ones once they are not needed anymore.
但是,對于像協作編輯器這樣的東西,您可能需要考慮使用 WebSockets 而不是一直發送請求.一個小的 HTTP 請求開銷很大,而 WebSocket 連接幾乎沒有開銷.
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.
這篇關于Ajax 密集型頁面:重用同一個 XMLHttpRequest 對象還是每次都創建一個新對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!