Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - Is it more performant to use several for-loops by themself or to delegated the logic to promises?

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;

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...