Nodejs optimizations with c++ addons
--
Let's make service using node js to create ‘QR codes’(CPU intensive task) to understand how can we use C++ for optimizations.
Results for generating 10000 Qr Codes:
C++ single thread:2960.125ms
Nodejs: 19180.051ms
Node js code to generate QR codes:
Following steps for C++:
Step 1: package.json
We need to add “gypfile” flag as true and dependencies.
Step 2: Create DataProcessingAsyncWorker.h (addon folder)
Header file that we will need further.
Step 3: Create DataProcessingAsyncWorker.cc (addon folder)
Here we write processing logic.
Step 4: Create Addon.cc (addon folder)
Here we have c++ function (ProcessData) which we can call from javascript and which will execute our main processing logic on a separate thread by adding it to worker queue.
Step 5: Install C++ dependencies
Step 6: Create binding.gyp
Step 7: Npm install
Npm install will build C++ files and it can be used in node js as follows:
And we are done with code walkthrough!
Every request will be added to a new thread. Let's try with 2 concurrent requests for 50,000 and 40,000 codes.
Here we can see parallel processing of 2 requests on separate threads(Multithreading).
Conclusion
We saw how easy it is to optimize node js for CPU intensive tasks using c++.
Source code: https://github.com/riddheshganatra/qrcodenodecpp