Why v8-fast-api-calls function in a object is much slower than normal function?

177 views
Skip to first unread message

车雄生

unread,
Aug 3, 2023, 6:55:03 PM8/3/23
to Chromium-dev
nodejs addon:
```c++
#include <node.h>
#include <v8-fast-api-calls.h>

int Add(int a, int b) {
    return a + b;
}

static void Add_Wrap(const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();
  int a = info[0]->Int32Value(context).ToChecked();
  int b = info[1]->Int32Value(context).ToChecked();

  info.GetReturnValue().Set(Add(a, b));
}

NODE_MODULE_INIT(/* exports, module, context */) {
  v8::Isolate* isolate = context->GetIsolate();

  exports->Set(context,
               v8::String::NewFromUtf8(isolate, "Add").ToLocalChecked(),
               v8::FunctionTemplate::New(isolate, Add_Wrap)
                  ->GetFunction(context).ToLocalChecked()).FromJust();

  static v8::CFunction FastAdd(v8::CFunction::Make(Add));
  exports->Set(
    context, v8::String::NewFromUtf8Literal(isolate, "FAdd"),
    v8::FunctionTemplate::New(
            isolate, Add_Wrap, v8::Local<v8::Value>(),
        v8::Local<v8::Signature>(), 0, v8::ConstructorBehavior::kThrow,
                              v8::SideEffectType::kHasSideEffect, &FastAdd)
        ->GetFunction(context).ToLocalChecked()).FromJust();
}
```
javascript test code:
```javascript
const path = require('path');
const Calc = require('node-gyp-build')(__dirname);

const LOOP_COUNT = 1000000;

let beginTime = new Date();
for(var i = 0; i < LOOP_COUNT; i++) {
    Calc.Add(12, 34);
}
let endTime = new Date();
console.log (`${LOOP_COUNT} Calc.Add using ${(endTime.getTime() - beginTime.getTime())}ms`);

beginTime = new Date();
for(var i = 0; i < LOOP_COUNT; i++) {
    Calc.FAdd(12, 34);
}
endTime = new Date();
console.log (`${LOOP_COUNT} Calc.FAdd using ${(endTime.getTime() - beginTime.getTime())}ms`);

const FAdd = Calc.FAdd

beginTime = new Date();
for(var i = 0; i < LOOP_COUNT; i++) {
    FAdd(12, 34);
}
endTime = new Date();
console.log (`${LOOP_COUNT} FAdd using ${(endTime.getTime() - beginTime.getTime())}ms`);
```
command & result:

```bash
v8api_perf$ node --turbo-fast-api-calls perf.js
1000000 Calc.Add using 11ms
1000000 Calc.FAdd using 95ms
1000000 FAdd using 3ms
```

Reply all
Reply to author
Forward
0 new messages