##CS378 Summer 2015: Marek Bejda
##CS N378 Generic Programming and the STL Library Week 7
So a couple of weeks back I wrote about finding something to do with C++. As a web developer I couldn’t see many uses on the front end or serving content, but that’s because I wasn’t asking the right questions. (True Detectives) So a couple of days ago I realized NodeJS supports C++ modules and ever since I’ve been hooked. Stumbled across this super useful Github repo node-cpp-modules. It starts off from the basics, a hello world module, but goes pretty deep even objects and threads very quick.
So the barebones code for a C++ node module goes like:
So cool but why use C++ if we can just write the same stuff in Javascript?
Well performance of course! For comparison I took our Collatz code from Week 1 and easily transformed it into a module. And also translated it into Javascript.
modulename.cpp
To compile the C++ module we just need to do npm build . then we have a runner script called run.js
now to run the module we just node run.js
collatz.js
to run the native module we just node collatz.js.
Okay with the two scripts ready to go we can time them.
From the results we can clearly see that the C++ version is much faster at finding the max cycle length from 100000 to 410000. Javascript is almost 5 times slower.
##Tip of the Week:
For this week I have like 20 tips, but to keep it simple I’ll just share 2. Well the first one was above I strongly recommend checking out the C++ modules repo. I also recommend playing with emcscripten.
Emscripten is an LLVM-to-JavaScript compiler. It takes LLVM bitcode - which can be generated from C/C++, using llvm-gcc (DragonEgg) or clang, or any other language that can be converted into LLVM - and compiles that into JavaScript, which can be run on the web (or anywhere else JavaScript can run).