I have a function that is somewhat computationally expensive, we are talking about 2–5ms here.
function heavyWork() {
// ...
}
heavyWork()
gets called a couple hundert times by different parts of my code at once which blocks Node.js' event loop. I was thinking about moving it to a child process by using child_process.fork
, however even just sending ~500 IPC messages takes about the same time as computing it in the main process. Theoretically I could live with this solution, it's just a bit slower than before and does not block the event loop, though I would like to speed things up.
The other thing I tried was using Worker Threads. However spawning that many threads was obviously even slower than the previous approach.
I will probably have to find a way to batch messages before sending them to the worker process unless there is a way of achieving this in Node that I have not tried yet. Any ideas?
Copyright Notice:Content Author:「dislick」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/61250251/quickest-way-to-call-a-computationally-expensive-function-many-times-in-node-js