-
Notifications
You must be signed in to change notification settings - Fork 459
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C++ addon is slower than js #790
Comments
Hi @D-Andreev,
In your case you could achieve at better performance using If you have time maybe could red this beautiful article: https://medium.com/the-node-js-collection/speed-up-your-node-js-app-with-native-addons-5e76a06f4a40 if you want to know something more specific just ask. |
Thanks for the info @NickNaso, I'm not completely sure but I think the example I provided above is just too simple and v8 has some optimisations in place when executing the js code, that's why it was performing better than c++ addon. When I run my example for getting nth prime number: Napi::Value MyAddon::isPrime(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (!info[0].IsNumber()) {
Napi::TypeError::New(env, "You need to provide a valid number")
.ThrowAsJavaScriptException();
return env.Null();
}
int n = info[0].ToNumber().Int64Value();
bool isPrime = true;
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
return Napi::Boolean::New(env, isPrime);
} the performance for c++ addon is indeed better than js: JsIsPrime*10000: 1191.665ms
CppIsPrime*10000: 849.511ms
JsIsPrime*10000: 1172.146ms
CppIsPrime*10000: 888.883ms |
Hi @D-Andreev, |
Hi @D-Andreev,
|
I agree with @NickNaso. Communicating between the JS code and the native code is expensive. Therefore native addons only provide an advantage over pure JS if significant work is being done on the native side for each transition between JS code and native code. |
Hi @D-Andreev, |
Hi,
We are considering rewriting some of our nodejs modules into native addons in C++, so I'm creating a small POC to show the performance difference. Unfortunately with the code I've written so far, c++ addon is actually slower than js code. This seems very strange so I wanted to share it here, I must be doing something wrong...
I'm sending an array of values to c++ addon and removing all values which are
false
from it. I have the same implementation in js.Results from running both:
As you can see
CppFunc
is much slower that vanilla js implementation. I suspect that the slow performance comes from casting to napi array:Napi::Array arr = info[0].As<Napi::Array>();
, because if I remove this and construct the array in c++, then it's faster.Any ideas?
The text was updated successfully, but these errors were encountered: