javascript 处理 AJAX 调用的 Web Workers - 优化矫枉过正?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18768452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Web Workers handling AJAX calls - optimisation overkill?
提问by Konrad Dzwinel
I'm working with a code that handles all AJAX requests using Web Workers (when available). These workers do almost nothing more than XMLHttpRequest
object handling (no extra computations). All requests created by workers are asynchronous (request.open("get",url,true)
).
我正在处理使用 Web Workers(如果可用)处理所有 AJAX 请求的代码。这些工人几乎只做XMLHttpRequest
对象处理(没有额外的计算)。工作人员创建的所有请求都是异步的 ( request.open("get",url,true)
)。
Recently, I got couple of issues regarding this code and I started to wonder if I should spend time fixing this or just dump the whole solution.
最近,我遇到了一些关于此代码的问题,我开始怀疑是否应该花时间解决这个问题,或者只是转储整个解决方案。
My research so far suggests that this code may be actually hurting performance. However, I wasn't able to find any credible source supporting this. My only two findings are:
到目前为止,我的研究表明这段代码实际上可能会损害性能。但是,我找不到任何可靠的来源来支持这一点。我唯一的两个发现是:
- 2 year old jQuery feature suggestionto use web workers for AJAX calls
- thisSO question that seems to ask about something a bit different (using synchronous requests in web workers vs AJAX calls)
- 使用 Web Worker 进行 AJAX 调用的2 岁jQuery 功能建议
- 这个SO question 似乎询问了一些不同的东西(在 Web Worker 和 AJAX 调用中使用同步请求)
Can someone point me to a reliable source discussing this issue? Or, are there any benchmarks that may dispel my doubts?
有人可以指出我讨论这个问题的可靠来源吗?或者,是否有任何基准可以消除我的疑虑?
[EDIT] This question gets a little bit more interesting when WebWorker is also responsible for parsing the result (JSON.parse
). Is asynchronous parsing improving performance?
[编辑] 当 WebWorker 还负责解析结果 ( JSON.parse
)时,这个问题会变得更有趣。异步解析能提高性能吗?
采纳答案by Konrad Dzwinel
I have created a proper benchmark for that on jsperf. Depending on the browser, WebWorker approach is 85-95% slowerthan a raw ajax call.
我在 jsperf 上为此创建了一个适当的基准。根据浏览器的不同,WebWorker 方法比原始 ajax 调用慢 85-95%。
Notes:
笔记:
- since network response time can be different for each request, I'm testing only
new XMLHttpRequest()
andJSON.parse(jsonString);
. There are no realAJAX calls being made. - WebWorker setup and teardown operations are notbeing measured
- note that I'm testing a single request, results for webworker approach may be better for multiple simultaneous requests
- Calvin Metcalf explained to me that comparing sync and async on jsperf won't give accurate results and he created another benchmarkthat eliminates async overhead. Results still show that WebWorker approach is significantly slower.
- From the Reddit discussionI learned that data passed between the main page and WebWorker are copied and have to be serialized in the process. Therefore, using WebWorker for parsing only doesn't make much sense, data will have to be serialized and deserialized anyway before you can use them on the main page.
- 由于每个请求的网络响应时间可能不同,因此我仅测试
new XMLHttpRequest()
和JSON.parse(jsonString);
. 没有进行真正的AJAX 调用。 - 未测量WebWorker 设置和拆卸操作
- 请注意,我正在测试单个请求,对于多个同时请求,webworker 方法的结果可能更好
- Calvin Metcalf 向我解释说,在 jsperf 上比较同步和异步不会给出准确的结果,他创建了另一个消除异步开销的基准。结果仍然表明 WebWorker 方法要慢得多。
- 从Reddit 的讨论中我了解到,在主页和 WebWorker 之间传递的数据被复制,并且必须在此过程中进行序列化。因此,仅使用 WebWorker 进行解析没有多大意义,数据无论如何都必须进行序列化和反序列化,然后才能在主页上使用它们。
回答by Calvin
First thing to remember is that web workers rarely make things faster in the sense of taking less time, they make things faster in the sense that they off load computation to a background thread so that processing related to user interaction is not blocked. For instance when you take into account transferring the data, doing a huge calculation might take 8 seconds instead of 4. But if it was done on the main thread the entire page would be frozen for 4 seconds which is likely unacceptable.
首先要记住的是,网络工作者很少在花费更少时间的意义上使事情变得更快,他们使事情变得更快,因为他们将计算卸载到后台线程,以便与用户交互相关的处理不会被阻止。例如,当您考虑传输数据时,进行大量计算可能需要 8 秒而不是 4 秒。但如果在主线程上完成,整个页面将被冻结 4 秒,这可能是不可接受的。
With that in mind moving just the ajax calls off the main thread won't gain you anything as ajax calls are non blocking. But if you have to parse JSON or even better, extract a small subset out of a large request then a web worker can help you out.
考虑到这一点,仅将 ajax 调用移出主线程不会为您带来任何好处,因为 ajax 调用是非阻塞的。但是,如果您必须解析 JSON 甚至更好,从大型请求中提取一小部分,那么网络工作者可以帮助您。
A caveat i've heard but not confirmed is that workers use a different cache than the main page so that if the same resources are being loaded in the main thread and the worker it could cause a large duplication of effort.
我听说过但未证实的一个警告是,worker 使用与主页面不同的缓存,因此如果在主线程和 worker 中加载相同的资源,则可能会导致大量重复工作。
回答by Radu Potop
You are optimizing your code in the wrong place.
您在错误的地方优化了代码。
AJAX requests already run in a separate thread and return to the main event loop once they fulfil (and call the defined callback function).
AJAX 请求已经在单独的线程中运行,并在完成后返回主事件循环(并调用定义的回调函数)。
Web workers are an interface to threads, meant for computationally expensive operations. Just like in classical desktop applications when you don't want to block the interface with computations that take a long time.
Web Worker 是线程的接口,用于计算成本高的操作。就像在经典桌面应用程序中一样,当您不想用需要很长时间的计算来阻塞接口时。
回答by jsan
Asynchronous IO is an important concept of Javascript.
异步IO是Javascript的一个重要概念。
First, your request is already asynchronous, the IO is non-blocking and during your request, you can run any another Javascript code. Executing the callback in a worker is much more interesting than the request.
首先,您的请求已经是异步的,IO 是非阻塞的,并且在您的请求期间,您可以运行任何其他 Javascript 代码。在工作线程中执行回调比请求有趣得多。
Second, Javascript engines execute all code in the same thread, if you create new threads, you need to handle data communication with the worker message api(see Semaphore).
其次,Javascript引擎在同一个线程中执行所有代码,如果创建新线程,则需要处理与worker message api的数据通信 (参见Semaphore)。
In conclusion, the asynchronous and single-threaded nature of JavaScript is powerful, use it as much as possible and create workers only if you really need it, for example in a long Javascript process.
总之,JavaScript 的异步和单线程特性是强大的,尽可能多地使用它,并且只有在你真正需要它时才创建 worker,例如在一个很长的 Javascript 进程中。
回答by transformerTroy
From my experience, Web Workers should notbe used for AJAX calls. First of all, they are asynchronous, meaning code will still run while you're waiting for the information to come back.
根据我的经验,不应将Web Workers用于 AJAX 调用。首先,它们是异步的,这意味着在您等待信息返回时代码仍会运行。
Now, using a worker to handle the response is definitely something you could use the Web Worker for. Some examples:
现在,使用 worker 来处理响应绝对是您可以使用 Web Worker 的事情。一些例子:
- Parsing the response to build a large model
- Computing large amounts of data from the response
- Using a Shared Web Worker with a template engine in conjunction with the AJAX response to build the HTML which will then be returned for appending to the DOM.
- 解析响应以构建大型模型
- 从响应中计算大量数据
- 使用带有模板引擎的 Shared Web Worker 以及 AJAX 响应来构建 HTML,然后将其返回以附加到 DOM。
Edit: another good read would be: Opinion about synchronous requests in web workers
编辑:另一个不错的读物是:关于网络工作者同步请求的意见