gpt4 book ai didi

javascript - 自己使用几个 for 循环还是将逻辑委托(delegate)给 promise 性能更好?

转载 作者:搜寻专家 更新时间:2023-10-30 21:14:50 24 4
gpt4 key购买 nike

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

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;

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

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

哪种方式性能更好?有更好的方法吗?感谢您的帮助!

最佳答案

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 。 Promises 不会“使”任何东西异步,甚至不会启用类似多线程的并行性。

关于javascript - 自己使用几个 for 循环还是将逻辑委托(delegate)给 promise 性能更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52444863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com