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

后端 未结 3 1012
一向
一向 2020-12-12 01:16

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-lo

相关标签:
3条回答
  • 2020-12-12 01:26

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

    No, because promises don't make anything asynchronous or parallel. They can only be used to observe things that are already asynchronous or parallel.

    All that throwing promises at that code would do is change when the main thread blocks and add overhead.

    If you need to offload or parallelize long-running computational tasks, look at web workers.

    0 讨论(0)
  • 2020-12-12 01:29

    The code would not be any more performant.

    JavaScript is typically single-threaded (unless you use web workers), so your code wouldn't complete any more quickly using promises (because the loops wouldn't run in parallel)—in fact, if anything, it might be imperceptibly slower.

    A promise is more of a way to handle the outcome of asynchronous code, and not a way to cause code to run asynchronously.

    0 讨论(0)
  • 2020-12-12 01:32

    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.

    0 讨论(0)
提交回复
热议问题