问题描述
我正在开发,其中包括地图/减少可以异步迭代的序列上的函数。
I'm working on a JavaScript library that provides, among other things, map/reduce functions on sequences that can be iterated asynchronously.
A ,在这种情况下使用 setImmediate
似乎更有意义 nextTick
显然是等待提前挂起的I / O事件,这对我来说似乎不好。
According to the answer to another question on SO, it seems that it would probably make more sense to use setImmediate
in this case as nextTick
apparently jumps ahead of pending I/O events, which seems bad to me.
:
所以我是对的,并且异步迭代序列应该完成使用 setImmediate
?或者 nextTick
在这里是一个更好的选择? (在任何一种情况下,一个明确的解释为什么将非常感激。)
So am I right, and iterating over sequences asynchronously should be done with setImmediate
? Or would nextTick
be a better choice here? (In either case, a clear explanation why would be much appreciated.)
推荐答案
一些注意事项:
我首先要对setImmediate的扩展速度比 process.nextTick
做更严格的基准测试。如果它没有(太慢),我会立即去 setImmediate
,因为这不会使事件循环挨饿。
I'd first do serious benchmarks to what extend setImmediate is slower than process.nextTick
. If it's not (much) slower, I'd go for setImmediate
straight away since that won't starve the event loop.
在节点0.10中有一个硬限制(1000,请参阅)你可以递归调用nextTick多少次,所以你应该防止在任何情况下发生这种情况。您需要在迭代之前选择策略,或者能够在迭代期间更改策略(同时检查当前迭代计数)。
In node 0.10 there's a hard limit (1000, see node.js docs) to how many times you can recursively call nextTick, so you should prevent that from happening in any case. You either need to choose a strategy before iteration, or be able to change strategy during iteration (while checking for current iteration count).
如果选择process.nextTick以获得性能原因,你可能想要设置一个可配置的硬限制,连续多少次 process.nextTick
,然后切换到 setImmediate
。我没有在nodejs上有严重工作量的经验,但我认为如果你的库使他们的I / O不稳定,人们就不会喜欢它。
If you choose process.nextTick for performance reasons, you might want to set a configurable hard limit for how many times it would do process.nextTick
in a row, and else switch to setImmediate
. I don't have experience with serious work loads on nodejs, but I do think people are not gonna like it if your library makes their I/O choppy.
setImmediate will肯定是最安全的,总而言之。
setImmediate would certainly be safest, all in all.
至于浏览器:
我没有研究过您的图书馆,但因为您实际上是来自 setTimeout
,您可以通过 window.postMessage
帮助您了解新的延迟技术,什么不是。有一个很好的小型库,名为(但语义不同于节点next-tick!)并且有一个用于setImmediate 的跨浏览器填充程序,这是相当重的因为1)它需要实现setImmediate规范(包括取消预定的能力)任务)和2)它有更广泛的浏览器兼容性。
As for the browser:I haven't studied your library, but since you are actually coming from setTimeout
, you may be helped learning about the new breed of delay techniques via window.postMessage
and what not. There's a nice and small library called next-tick (but with different semantics than node next-tick!) and there's a cross-browser shim for setImmediate, which is quite a bit heavier because 1) it needs to implement the setImmediate spec (including ability to cancel scheduled tasks) and 2) it has much wider browser compatibility.
看看这个将setImmediate(shim)与setTimeout进行比较。
Check out this async sorting demo comparing setImmediate (shim) to setTimeout.
这篇关于我应该使用process.nextTick或setImmediate进行异步迭代吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!