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 match
es in parallel will still take the same amount of time as running each match
sequentially, as before.
Is my understanding correct?
Thanks, Asim