Speed up Your Node.js App with Native Addons
If your Node app’s sole purpose is to compute prime numbers and you don’t want to use a fast lookup table, please rely on this benchmark 100%. For anything else, this benchmark is probably useless.
If we use
intas the parameter for C++’s
We could easily improve the algorithm. But since we’re not interested in absolute performance, it doesn’t matter as long as both implementations use the same algorithm.
The implementation of the algorithm in
primes.cc is exactly the same as in
primes.js modulo syntax. What’s different in the addon is how the function
prime() is exported:
This example uses the N-API for the Node.js Native Addon. The N-API is a C API that ensures stability of the Application Binary Interface (ABI) across versions of Node.js. That means, compiled once, the module can be used for different versions of Node (8 and higher) without re-compilation. As C++ is often more convenient than C, we use a C++ wrapper package, node-addon-api. For more info on getting started with N-API check out the documentation or GitHub repository.
Method converts the first argument to a number, calls the C++ function
Init function sets
Method as property
prime on the exported module.
--no-opt flag, e.g.., by running
node --no-opt index.js.
The full prime number example is hosted on GitHub. Fork it and experiment with it. Remember to run
npm install to recompile the addon if you change any C++ code.
All computations were run on a MacBook Air with Node 9.2.
Thanks to Andreas Haas, Anna Henningsen, and Michael Dawson for careful reviews.