Synchronous addon will block the event loop of Node.js. But perhaps, exists a "standard" limit admissible to block the event loop.
var results = addon.my_function(parameters); //consumes 2ms
My function consumes 2 ms. At this moment I am wondering if the work of change it to asynchronous way pays off the final performance.
As you likely know node.js has a concurrency model which only addresses concurrency of IO bound tasks. Any serial task that is not broken up will pause the event loop for that duration. It is possible to implement routines to break this task up, but it only suite specific paradigms. If you're doing a single operation which is going to take a lot of time then you should look into parallelism. If you're processing a dataset, like an array or a file line-by-line you could implement a recursive function to replace a loop and when you recurse instead of calling your function directly you can delay it with setTimeout so that you can resume your eventloop to avoid halting it for too long(to where timeout occur).
I cannot give you an exact time to which a synchronous task would be considered "too long". It really depends. There are far too many factors. How often this task occurs really makes a difference.
There are multiple approaches to handling these kinds of tasks:
If you're process is taking 2ms, it's likely that you'll be fine just letting the event loop handle it. Blocking the event loop for 2ms isn't a big deal. If these types of tasks are frequent(multiple times a second), then you may want to consider offloading to a worker or possibly creating some kind of queue or some method to limit how many are getting processed at a time. Otherwise you could stumble upon issues with slow responses. For now I think you'll be fine unless this is a very common task.
If your task is IO bound, the work of changing this to an asynchronous should be trivial, as nodejs is built from the ground up with this paradigm. It is bad practice if you do not use asynchronous methods when possible. Though this is only related to IO. If you're task is not reading/writing data to/from some source then asynchronous methods will do absolutely nothing for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With