As you know, NodeJs is a non-blocking I/O platform which gives you ability to do non-blocking and event-based functionalities. It has async methods for I/O but it also provide sync version of that methods as well. It means you can write to a file with async/non-blocking methods and you can do the same with sync methods.
So, in this post I want to show you the different between using async or non-blocking I/O and sync I/O. Here I have a HTTP server which has a simple functionality, it just reads a static file from disk and gives the content of file to the user by an HTTP request. There’s two different ways for reading a file from disk in NodeJs, with fs.open (async) or fs.openSync (sync).
Results speak for themselves, as expected. When we try to read a file with Async mode, all steps of reading a file (stat, open, read, close) are async and it means the reading process will not block the request (less request time) but in Sync mode, each step should wait for previous step result so it takes more than Async mode.
I used Apache Benchmark (ab) for these tests, with this parameters:
ab -n 1000 -c 1000 -vhr http://localhost:8081/
And the test system is:
CentOs, Linux 2.6.18-164.el5 and NodeJs v0.8.8, 512MB Memory, QEMU Virtual CPU.
Well, let’s see the results.
Time taken for tests: 3.800 seconds Requests per second: 263.19 [#/sec] (mean) Time per request: 3799.512 [ms] (mean) Time per request: 3.800 [ms] (mean, across all concurrent requests) Percentage of the requests served within a certain time (ms) 50% 2667 66% 2682 75% 3752 80% 3752 90% 3761 95% 3765 98% 3765 99% 3765 100% 3765 (longest request)
Time taken for tests: 4.809 seconds Requests per second: 207.95 [#/sec] (mean) Time per request: 4808.944 [ms] (mean) Time per request: 4.809 [ms] (mean, across all concurrent requests) Percentage of the requests served within a certain time (ms) 50% 2418 66% 3152 75% 3585 80% 3827 90% 4320 95% 4551 98% 4712 99% 4760 100% 4809 (longest request)
You can see that in the Async mode you can process about 264 requests per second while in Sync mode it’s about 208.
I made this test to show the power of Async I/O functions in NodeJs and also to show the NodeJs developers that using Sync I/O functions is not a good solution for Callback Hell, there are several better approaches to solve the Callback Hell problem, keep using Async functions.
You can download and run this test yourself, I made a Github repo, here you can download them: https://github.com/afshinm/Async-Sync-IO-benchmark