javascript – 为什么在这种情况下,本机承诺似乎比chrome中的回调更快?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 为什么在这种情况下,本机承诺似乎比chrome中的回调更快?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2085字,纯文字阅读大概需要3分钟。
内容图文
这是jsperf:http://jsperf.com/promise-vs-callback
回调案例(211 Ops / s):
// async test
var d = deferred;
function getData(callback) {
setTimeout(function() {
callback('data')
}, 0)
}
getData(function(data) {
d.resolve()
})
承诺案例(614 ops / s):
// async test
var d = deferred;
function getData() {
return new Promise(function(resolve) {
setTimeout(function() {
resolve('data')
}, 0);
})
}
getData().then(function(data) {
d.resolve()
})
如你所见,承诺更快,但他们有更多的代码.问题是为什么会发生这种情况.
这里延迟是由jsperf定义的,以显示它作为异步测试的完成.
解决方法:
看起来神奇的技巧在于chrome如何设置setTimeout(fn,0)的最小延迟.
我搜索了它,我发现了这个:https://groups.google.com/a/chromium.org/forum/#!msg/blink-dev/Hn3GxRLXmR0/XP9xcY_gBPQJ
我引用了重要的部分:
The way timer clamping works is every task has an associated timer nesting level. If the task originates from a setTimeout() or setInterval() call, the nesting level is one greater than the nesting level of the task that invoked setTimeout() or the task of the most recent iteration of that setInterval(), otherwise it’s zero. The 4ms clamp only applies once the nesting level is 4 or higher. Timers set within the context of an event handler, animation callback, or a timer that isn’t deeply nested are not subject to the clamping.
在回调的情况下,setTimeout在另一个setTimeout的上下文中递归调用,因此最小超时为4ms.
在promise的情况下,setTimeout实际上不是递归调用的,所以最小超时为0(实际上不会是0,因为其他东西也必须运行).
那么我们怎么知道setTimeout是递归调用的呢?好吧,我们可以在jsperf或只使用benchmark.js进行实验:
// async test
deferred.resolve()
这将导致Uncaught RangeError:超出最大调用堆栈大小.这意味着,一旦调用deferred.resolve,测试就会在同一个tick / stack上再次运行.所以在回调的情况下,setTimeout在它自己的调用上下文中被调用并嵌套在另一个setTimeout中,这将把最小超时设置为4ms.
但是在承诺的情况下,然后根据promise规范和v8 doesn’t use setTimeout calling the callback after the next tick在下一个tick之后调用回调.它使用的东西必须类似于nodejs或setImmediate中的process.nextTick,而不是setTimeout.这会将setTimeout嵌套级别重置为0并使setTimeout延迟0ms.
内容总结
以上是互联网集市为您收集整理的javascript – 为什么在这种情况下,本机承诺似乎比chrome中的回调更快?全部内容,希望文章能够帮你解决javascript – 为什么在这种情况下,本机承诺似乎比chrome中的回调更快?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。