javascript – How to generate JsObject in Node.js c++ addon as fast as in pure js?
I am new as a Node.js cpp-addon developer, I need to return a very big Object from cpp(Node.js cpp-addon) to Javascript logic, here is my code:
cpp-addon case:
var addon = require('bindings')('addon.node')
console.time('perf');
console.log('This should be result:', addon.getBigObject('foo bar'));
console.timeEnd('perf');
#include <napi.h>
Napi::Value GetBigObject(const Napi::CallbackInfo& info) {
Napi::Env m_env = info.Env();
Napi::Object node = Napi::Object::New(m_env);
node.Set(Napi::String::New(m_env, "foo"), Napi::Number::New(m_env, 1));
node.Set(Napi::String::New(m_env, "body"), Napi::Array::New(m_env));
for (int i = 0; i < 2000000; i++) {
Napi::Object stmt = Napi::Object::New(m_env);
stmt.Set(Napi::String::New(m_env, "foo"), Napi::Number::New(m_env, 1));
Napi::Array body = node.Get("body").As<Napi::Array>();
auto len = std::to_string(body.Length());
body.Set(Napi::String::New(m_env, len), stmt);
}
return node;
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "getBigObject"), Napi::Function::New(env, GetBigObject));
return exports;
}
NODE_API_MODULE(addon, Init)
Running this code time cost:
perf: 2.782s
pure-js case:
var addon = require('./addon.js');
console.time('perf');
console.log('This should be result:', addon.getBigObject('var foo = 1;'));
console.timeEnd('perf');
module.exports.getBigObject = function() {
const node = {};
node.foo = 1;
node.body = [];
for (let i = 0; i < 2000000; i++) {
let body = node.body;
body.push({
foo: 1
});
}
return node;
}
Running this code time cost:
perf: 220.973ms
Why is this so slow that generate JsObject in cpp-addon?