简体   繁体   中英

speed of c++ addons for node.js

I made two similar codes on c++ and node.js, that just work with strings. I have this in .js file:

//some code, including f
console.time('c++');
console.log(addon.sum("123321", s));
console.timeEnd('c++');
console.time('js');
console.log(f("123321", s));
console.timeEnd('js');

and my c++ addon looks like that:

//some code, including f
void Sum(const v8::FunctionCallbackInfo<v8::Value>& args)
{
    v8::Isolate* isolate = args.GetIsolate();
    v8::String::Utf8Value str0(isolate, args[0]);
    v8::String::Utf8Value str1(isolate, args[1]);
    string a(*str0), b(*str1);
    string s2 = f(a, b);
    args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, s2.c_str()).ToLocalChecked());
}

but the problem is that c++ works nearly 1.5 times slower, than js, even though the function on JS has some parts, that can be optimised (I did not write it very accurately). In the console I get

@uTMTahdZ22d!a_ah(3(_Zd_]Zc(tJT[263mca!(jcT[20_]h0h_06q(0jJ(T]!&]qZM]d_30j&Tuj2hm[Z0d@!32ccT2(!dud@6]0MdJc]mta!3]j]_(hhJqha(([
c++: 7.970s
@uTMTahdZ22d!a_ah(3(_Zd_]Zc(tJT[263mca!(jcT[20_]h0h_06q(0jJ(T]!&]qZM]d_30j&Tuj2hm[Z0d@!32ccT2(!dud@6]0MdJc]mta!3]j]_(hhJqha(([
js: 5.062s

So, the results of functions are similar, but the JS program ran a lot faster. How can it be? Shouldn't c++ faster than JS (at least not so much slower)? Maybe I did not took in account an important detail, that slows c++ so much, or working with strings is really so slow in c++?

First off, the Javascript interpreter is pretty advanced in what types of optimizations it can do (actually compiling Javascript code to native code in some cases) which significantly reduces the differences between Javascript and C++ compared to what most people would think.

Second, crossing the C++/Javascript boundary has some overhead cost associated with it as you marshall the function arguments in between the Javascript world and the C++ world (creating copies, doing heap operations, etc...). So, if that overhead is significant relative to the execution of the operation, then it can negate your advantages to going to C++ in the first place.

For more detailed comments, we would need to see the actual implementation of f() in both Javascript and C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM