0

For my work, I am developing a NodeJS application. One of its features is to allow the user to upload an image, match it against a set of images stored on the server and return the best match. For matching, I'm using opencv4nodejs library. However, the matching algorithm is quite complicated and hence slow. Additionally, there are hundreds of screens in my search space to match against.

Right now, my code behaves in the following manner (pseudo-code):

async match(a: Buffer, b: Buffer): Promise<boolean> {
  // some lengthy calculation..
  return true/false;
}

async findMatches(image: Buffer): Promise<Buffer[]> {
  const ret = [];
  for (const item of this.imagesList) {
    const matches = await this.match(item, image);
    if (matches) ret.push(item);
  }
  return ret;
}

If I were to change the above to something like this:

async findMatches(image: Buffer): Promise<Buffer[]> {
  const ret = [];
  const promises = this.imagesList.map(it => {
    return this.match(item, image).then(matches => {
      if (matches) ret.push(item);
    });
  });
  await Promises.all(promises);
  return ret;
}

Should this speed up my code? I've written pseudo-code above as the actual codebase is large and distributed amongst many files. This is also the reason that I haven't already made the change and tested its pros and cons myself. So I am asking for your expert opinion.

My instinct is that it should not result in any measurable speed up. I believe this is because NodeJS is a single-threaded application. If the match function performs time-taking sequential tasks, then running any number of matches in parallel will still take the same amount of time as running each match sequentially, as before.

Is my understanding correct?

Thanks, Asim

AweSIM
  • 1,651
  • 4
  • 18
  • 37
  • 1
    You're correct, it will not result in any measurable speed up - what matters here is the size of your file, the size of searchable files, and the complexity of your comparison algo – Derek Pollard Apr 19 '19 at 14:28
  • Syntax sugar is supposed to speed up not your code, but your time to write this code :) – Styx Apr 19 '19 at 14:40
  • Promises don't speed up anything. They are just a means to make handling asynchronous code easier. If your code is not asynchronous, don't use promises. To scale your process, use worker threads (whose results will be asynchronous, and then you can reasonably use promises). – Bergi Apr 19 '19 at 15:36

0 Answers0