Nodejs - Promise.all与标准async/await的性能比较

mccptt67  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(249)

我仍然在尝试理解Promise. all,所以写了一个简单的脚本来查看Promise. all与使用while循环等待每个函数之间的性能差异。
我假设Promise. all会快很多,因为它并行运行函数,但我的脚本似乎告诉我不是这样。
这是不是太简单了,我错过了什么?

const p1 = async () => {
  let x = 0
  
  while(x < 100000000) {
    x++
  }
  return x
}

const p2 = async () => {
  let y = 100000000
  
  while(y > 0) {
    y--
  }
  return y
}

const p3 = async () => {
  let z = 0
  
  while(z < 200000000) {
    z = z + 2
  }
  return z
}

const run1 = async () => {
   console.time("Parallel")
   
   const [res1, res2, res3] = await Promise.allSettled([p1(), p2(), p3()])
   console.log(res1.value, res2.value, res3.value)
   
   console.timeEnd("Parallel")
}

const run2 = async () => {
   console.time("Sync")
   
   const res1 = await p1()
   const res2 = await p2()
   const res3 = await p3()
   console.log(res1, res2, res3)
   
   console.timeEnd("Sync")
}

run1()
// run2()
    • 结果**

v09wglhw

v09wglhw1#

不要忘记js是单线程的,所以主线程上的计算是以牺牲其他函数为代价的,所以例如p1和p2“并行”运行,但在同一个事件循环上。

const p1 = async () => {
  let x = 0
  while(x < 100000000) {x++}
  return x
}
const p2 = async () => {
  let y = 100000000
  while(y > 0) {y--}
  return y
}
const p3 = async () => {
  let z = 0
  while(z < 200000000) {z = z + 2}
  return z
}

const run1 = async () => {
   console.time("Parallel")
   const [res1, res2, res3] = await Promise.all([p1(), p2(), p3()])
   console.timeEnd("Parallel")
}
const run2 = async () => {
   console.time("Sync")
   const res1 = await p1()
   const res2 = await p2()
   const res3 = await p3()
   console.timeEnd("Sync")
}

const p4 = async () => {
  return new Promise(resolve => {
    timeout = setTimeout(() =>  {
      resolve(true);
    }, 100);
  });
}
const p5 = async () => {
  return new Promise(resolve => {
    timeout = setTimeout(() =>  {
      resolve(true);
    }, 150);
  });
}
const p6 = async () => {
  return new Promise(resolve => {
    timeout = setTimeout(() =>  {
      resolve(true);
    }, 200);
  });
}

const run3 = async () => {
   console.time("Parallel2")
   const [res1, res2, res3] = await Promise.all([p4(), p5(), p6()])
   console.timeEnd("Parallel2")
}
const run4 = async () => {
   console.time("Sync2")
   const res1 = await p4()
   const res2 = await p5()
   const res3 = await p6()
   console.timeEnd("Sync2")
}

(async()=>{
  await run1()
  await run2()
  await run3()
  await run4()
})()

正如你在第二个例子中看到的,对于非计算密集型任务,Promise.all需要的时间与它最长的promise一样长,而链接则需要所有promise的总和。

相关问题