Szymon Wygnański
Szymon Wygnański

Reputation: 11064

Comparing nodejs c++ addon's speed with js equivalent?

I've got a nodejs programm in which I do a lot of computations. I was thinking about making it faster so i decided that I will try to move some code to c++. But first I've performed a quick test to see if the performance boost is significant.

I know that calling a c++ function in a v8 is expensive so in my test there is only one call!

binding.gyp file:

{
  "targets": [
    {
      "target_name": "test",
      "sources": [ "test.cc" ]
    }
  ]
}

test.cc file:

#include <node.h>
#include <v8.h>
#include <cstdlib>
#include <time.h>

using namespace v8;

Handle<Value> Func(const Arguments& args) {
  HandleScope scope;
  double sum = 0;
  double x = rand() / RAND_MAX;
  double y = rand() / RAND_MAX;

  for (int i = 0; i < 1e9; i += 1) {
    x = x / y;
    y = x * rand() / RAND_MAX;
    sum += x + y;
  }

  return scope.Close(Number::New(sum));
}

void init(Handle<Object> exports) {
  srand(time(NULL));
  exports->Set(String::NewSymbol("func"),
      FunctionTemplate::New(Func)->GetFunction());
}

NODE_MODULE(test, init)

test.js file:

'use strict';

var cpp = require("./build/Release/test").func;

function js() {
  var sum = 0;
  var x = Math.random();
  var y = Math.random();

  for (var i = 0; i < 1e9; i += 1) {
    x = x / y;
    y = x * Math.random();
    sum += x + y;
  }

  return sum;
}

function log(msg, hrtime) {
  console.log(msg, (hrtime[0] * 1e9 + hrtime[1]) * 1e-9);
}

var t = process.hrtime();
js();
log('JS', process.hrtime(t));

t = process.hrtime();
cpp();
log('CPP', process.hrtime(t));

The results:

JS 8.060747399 
CPP 15.041201326000001

Why c++ addon is so slow?

I'm using node v0.10.21

Upvotes: 3

Views: 885

Answers (2)

Esailija
Esailija

Reputation: 140228

The thought of "write perf sensitive parts in C++" is flawed in V8. It makes sense in python/php where the canonical interpreters are literally 10000x+ slower than javascript compiled by V8.

If you write JS with perf in mind you will easily reach a fast enough level. Although writing such JS is not really easy because pretty much every intuitive idiom is bad for performance.

Upvotes: 2

Gabriel Llamas
Gabriel Llamas

Reputation: 18427

The div operation is the most expensive, and you're using it 3 more times in comparison with the js code. Also, you don't know how random() is implemented. The random() code from c++ might be very different from the random() code from js, so don't make assumptions.

Upvotes: 2

Related Questions