Open ronag opened 1 month ago
@addaleax
@ronag this is the code for napi_create_external_buffer
napi_create_external_buffer(napi_env env,
size_t length,
void* data,
node_api_nogc_finalize nogc_finalize_cb,
void* finalize_hint,
napi_value* result) {
napi_finalize finalize_cb = reinterpret_cast<napi_finalize>(nogc_finalize_cb);
NAPI_PREAMBLE(env);
CHECK_ARG(env, result);
#if defined(V8_ENABLE_SANDBOX)
return napi_set_last_error(env, napi_no_external_buffers_allowed);
#endif
v8::Isolate* isolate = env->isolate;
// The finalizer object will delete itself after invoking the callback.
v8impl::BufferFinalizer* finalizer =
v8impl::BufferFinalizer::New(env, finalize_cb, nullptr, finalize_hint);
v8::MaybeLocal<v8::Object> maybe =
node::Buffer::New(isolate,
static_cast<char*>(data),
length,
v8impl::BufferFinalizer::FinalizeBufferCallback,
finalizer);
CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure);
*result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked());
return GET_RETURN_STATUS(env);
// Tell coverity that 'finalizer' should not be freed when we return
// as it will be deleted when the buffer to which it is associated
// is finalized.
// coverity[leaked_storage]
}
If you built a version of Node.js commenting out
// The finalizer object will delete itself after invoking the callback.
v8impl::BufferFinalizer* finalizer =
v8impl::BufferFinalizer::New(env, finalize_cb, nullptr, finalize_hint);
That would introduce a memory leak but might show if the slowness is in the base Node functionality or due to node-api overhead that might be optimized.
The main thing that we were thinking it would be good to understand is if the slowness is in node::Buffer::New
or the additional wrapping in node-api.
@vmoroz is going to play around a bit with the implementation as well to see what might be possible in terms of flatenning/removing overhead.
Removing the finalizer improves things.
Given the following example:
more than 50% of the time is spent with
napi_create_external_buffer
which I would assume should be a rather fast operation...