V8:为什么JavaScript中的函数调用比C ++的函数调用更快

v8: why is function call inside javascript faster as a function call from c++

本文关键字:函数调用 JavaScript V8 为什么      更新时间:2023-10-16

我有以下脚本:

var rnd = 0;
function test(){
    rnd += dummy();
}
for(i = 0; i < 10000000; i++)
    test();
log(rnd);
rnd = 0;

日志在终端上打印一些东西。Dummy是一个返回随机数的C ++回调函数:

void dummy(const v8::FunctionCallbackInfo<v8::Value> &args)
{
    args.GetReturnValue().Set(rand() % 10);
}

在 v8 中编译和运行它的时间是 828 毫秒

在此之后,我从 test 中获取 C++ 中的函数句柄,并在循环中调用它相同的数量。这需要 2195 毫秒。

为什么这么慢,有没有可能更快?

C++

剪:
 auto global = context->Global();
 auto function = v8::Local<v8::Function>::Cast(global->Get(v8::String::New("test")));
 auto start = chrono::high_resolution_clock::now();
 for(size_t i = 0; i < 10000000; i++) {
      function->Call(global, 0, 0);
 }
 auto milli = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start);
 cout << "time: " << milli.count() << endl;

答案很简单 - 在 JS/C++ 代码之间切换很慢。

当你从JavaScript调用C++代码V8时必须做跳闸JS代码(test函数)-> C++代码(dummy function)->JS代码(回到test函数)

当你调用从C++代码调用C++代码的 JavaScript 时,V8 必须做以下行程:C++代码 -> JS 代码(test函数)-> C++代码(dummy function)-> JS代码(返回test函数)-> C++代码。