自己使用多个 for 循环还是将逻辑委托给 promise 会更高效? [英] Is it more performant to use several for-loops by themself or to delegated the logic to promises?

查看:15
本文介绍了自己使用多个 for 循环还是将逻辑委托给 promise 会更高效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下场景:一个函数得到 3 个一定长度的数组,每个数组都需要迭代以找到匹配的对象.当找到对象时,for 循环中断并且不会调用下一个循环.在这种情况下无法合并数组.基本上是这样的:

Following scenario: A function gets 3 arrays of a certain length, each one of those needs to be iterated over to find a matching object. When the object is found, the for-loop breaks and the next one isn't called. The arrays can't be merged in this case. Basically like this:

for (let i = 0; i < array1.length; i++) {
  if (array1[i].id == matchingID) {
    returnValue = array1[i];
    break;
  }
}
if (!returnValue) {
  for (let i = 0; i < array2.length; i++) {
    if (array2[i].id == matchingID) {
      returnValue = array2[i];
      break;
    }
  }
}
if (!returnValue) {
  for (let i = 0; i < array3.length; i++) {
    if (array3[i].id == matchingID) {
      returnValue = array3[i];
      break;
    }
  }
}
return returnValue;

在这种情况下使用 Promise 会更有效吗,因为这样所有的 for 循环都可以同时工作?像这样,每个函数调用都会执行上面示例中的一个 for 循环(并解析找到的值):

Would using promises be more efficient in this case, since that way all for-loops can be worked at at the same time? Like this, with each function-call doing one of the for-loops (and resolving the found value) from the example above:

return new Promise((resolve) => {
  this.findMatchingIDInArray1(array1)
    .then(() => resolve(returnValue));
  this.findMatchingIDInArray2(array2)
    .then(() => resolve(returnValue));
  this.findMatchingIDInArray3(array3)
    .then(() => resolve(returnValue));
}) 

哪种方式更高效?有没有更好的方法来做到这一点?谢谢你的帮助!

Which way is more perfomant? Is there better way to do this? Thanks for your help!

推荐答案

在这种情况下使用 Promise 是否会更有效,因为这样可以同时运行所有 for 循环?

Would using promises be more efficient in this case, since that way all for-loops can be worked at at the same time?

不,你误解了 Promise 的作用.它们是使处理异步代码更容易的工具.您的用例中没有异步代码,因此您不能在此处使用 Promise.Promise 不会制造"任何异步内容,甚至不会启用类似多线程的并行性.

No, you misunderstood what promises do. They're a tool to make dealing with asynchronous code easier. There is no asynchronous code in your use case, so you cannot make use of promises here. Promises do not "make" anything asynchronous, or even enable multithreading-like parallelism.

这篇关于自己使用多个 for 循环还是将逻辑委托给 promise 会更高效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆