2

Is there any point to use promise all() to speed up an expensive computation ? For example:

// Expensive computation

const data = [1, 2, 3];

const f = (x) => {
  return x*x; // or a more complex formula
}

// No promises

const f_data = data.map(f);

// With promises

const f_data = Promise.all(data.map((e) => Promise((e) => f(e))).then(res => res).catch(...);

Will there be any actual difference in execution speed ?

  • 1
    Why would `Promise.all` speed up anything? The async tasks would still take the same time. Moreover, you don't seem to have async tasks. Running something as a promise doesn't actually spawn another process or equivalent. – VLAZ Nov 25 '20 at 21:00
  • See also https://stackoverflow.com/questions/53876344/proper-way-to-write-nonbloking-function-in-node-js – Bergi Nov 25 '20 at 21:19
  • "*Will there be any actual difference in execution speed?*" - yes, the promises solution will be slower since it creates a bunch of unnecessary objects. But not enough to matter if the computation is actually expensive. – Bergi Nov 25 '20 at 21:19

1 Answers1

0

No, if you want to speed up computations you have to use workers in order to leverage multithreading.

If you use Promise.all, all of the callbacks will be queued and will run in a single thread, one after the other.

Guerric P
  • 30,447
  • 6
  • 48
  • 86