Wednesday, 10 May 2017

Why is NodeJS C/C++ addon faster then pure C

I experiment with NodeJS Addons and I have this code in C:

int fib(int n) {
    if (n == 0) return 0;
    else if (n == 1) return 1;
    else return (fib(n-1) + fib(n-2));
}

int main(int argc, char *argv[]) {
    fib(atoi(argv[1]));
}

And this in NodejS Addon:

JS:

const addon = require('./build/Release/addon');
console.log(addon.fib(process.argv[2]));

C:

using namespace v8;

int fib(int n) {
    if (n == 0) return 0;
    else if (n == 1) return 1;
    else return (fib(n-1) + fib(n-2));
}

void Method(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    args.GetReturnValue().Set(Uint32::New(isolate, fib(args[0]->Uint32Value())));
}

void init(Local<Object> exports) {
    NODE_SET_METHOD(exports, "fib", Method);
}

NODE_MODULE(addon, init)

I try calculate fib() for number 50 and gets this results:

  • Clean C: 2m 36s
  • NodeJS Addon: 1m 22s

Could anybody explain why is NodeJS Addon faster then pure C? I'm not C/C++ expert but I assumed then pure C will be faster.

Thanks!



via Budry

No comments:

Post a Comment