Ajax 密集型页面:重用同一个 XMLHttpRequest 对象还是每次都创建一个新对象?

Ajax-intensive page: reuse the same XMLHttpRequest object or create new one every time?(Ajax 密集型页面:重用同一个 XMLHttpRequest 对象还是每次都创建一个新对象?)

本文介绍了Ajax 密集型页面:重用同一个 XMLHttpRequest 对象还是每次都创建一个新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发某种在线多用户编辑器/合作界面,它将在一个页面的生命周期内执行大量(如数千个)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)

  1. 创建一个 XMLHttpRequest 对象并为每个 HTTP 请求重用它

  1. 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 对象还是每次都创建一个新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Ajax 密集型页面:重用同一个 XMLHttpRequest 对象还是每次都创建一个新对象?

基础教程推荐