Nodejs optimizations with c++ addons

Riddhesh Ganatra
3 min readNov 30, 2019

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

We at Code B are a team of Fullstack software developers, passionate and dedicated to growing businesses for clients.

We have experience in Web Applications(Frontend and Backend), Mobile Applications(Native and Hybrid), DevOps (AWS, GCP, Azure, Digital Ocean, and Heroku), Blockchain(Solana), and UI/UX Design(Figma).

Contact us if you need any help with Software.

--

--

Riddhesh Ganatra

Software Architect, Full Stack Web developer, MEAN/MERN stack, Microservices, etc