![](/img/trans.png)
[英]Why is recursion faster than a flat for loop for a summation function on JavaScript?
[英]Why is this loop in a then callback faster than in an async function?
当我出于学习目的而使用 TS 时,我发现 then 回调所需的时间少于带有 await 的异步 function。 这是我的代码片段:
带有异步/等待的代码:
const asyncCodeBlocker = async function(){ console.log("notAsync") await Promise.resolve(); console.time("async"); let i = 0; while (i < 1000000000) { i++; } console.timeEnd("async"); return 'billion loops done with async'; } asyncCodeBlocker().then(v => {console.log(v)}) console.log("mainStack")
结果:
notAsync
mainStack
async: 2.464s
billion loops done with async
带有嵌套 promise 的代码:
const promiseCodeBlocker = function(){ console.log("notAsyncInPromise") return Promise.resolve().then(() => { console.time("promise"); let i = 0; while (i < 1000000000) { i++; } console.timeEnd("promise"); return 'billion loops done with nested promise'; }) } promiseCodeBlocker().then(v => {console.log(v)}) console.log("mainStack")
结果:
notAsyncInPromise
mainStack
promise: 497.627ms
billion loops done with nested promise
为什么会这样?
原始代码是用 TypeScript 编写的,但在社区成员在 JS 中发布问题后,它被编辑和覆盖,以便能够运行代码片段。
事实证明,该行为是由我的 TS 配置引起的。 我将编译器选项“target”设置为es5 。 将其值更改为es6后,我设法为两个片段获得了相同的结果。
原始代码和结果:
带有异步/等待的代码:
const asyncCodeBlocker: () => Promise<any> = async function(){
console.log("notAsync")
await Promise.resolve();
console.time("async");
let i = 0;
while (i < 1000000000) { i++; }
console.timeEnd("async");
return 'billion loops done with async';
}
asyncCodeBlocker().then(v => {console.log(v)})
console.log("mainStack")
结果:
notAsync
mainStack
async: 2.464s
billion loops done with async
带有嵌套 promise 的代码:
const promiseCodeBlocker: () => Promise<any> = function(){
console.log("notAsyncInPromise")
return Promise.resolve().then(() => {
console.time("promise");
let i = 0;
while (i < 1000000000) { i++; }
console.timeEnd("promise");
return 'billion loops done with nested promise';
})
}
promiseCodeBlocker().then(v => {console.log(v)})
console.log("mainStack")
结果:
notAsyncInPromise
mainStack
promise: 497.627ms
billion loops done with nested promise
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.