Alignment or initialization requirements for Node-API external buffers #5047
Replies: 0 comments 8 replies
-
There is no strict alignment requirement for pointers passed to napi_create_external_buffer.. However, it is generally a good practice to align data structures to improve performance, especially on architectures with strict alignment requirements. Misaligned data access can result in performance penalties, such as extra memory accesses.. As for initializing the memory used for the buffer, it is not strictly necessary, but it is recommended to avoid potential issues with uninitialized memory. |
Beta Was this translation helpful? Give feedback.
-
Thanks for coming back. Can I ask: is your reply based on specific knowledge of the inner workings of Node-API/V8, or advice on good practice more generally? If the first, could you possibly point me in the direction of what in the code base (or perhaps a comment from one of the maintainers in another issue) gives you confidence in these conclusions (as they apply specifically to Node-API)? |
Beta Was this translation helpful? Give feedback.
-
The answer is based on my experience and I have read about it somewhere but currently unable to locate where. But a comment from a maintainer would be great. You can tag the maintainers to comment on this. |
Beta Was this translation helpful? Give feedback.
-
thankyou |
Beta Was this translation helpful? Give feedback.
-
Not for arraybuffers but there is (or can be) when the arraybuffer is used to back a typed array.
Yes. Even on e.g. x86_64, where misaligned loads and stores are usually free, except when they cross a cache line boundary.
Yes. GIGO. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Affected URL(s)
https://nodejs.org/dist/latest-v19.x/docs/api/n-api.html#napi_create_external_arraybuffer
Description of the problem
I am wondering if there are any requirements not stated in the docs for
napi_create_external_buffer
/napi_create_external_arraybuffer
:napi_create_external_buffer
etc?On JS side alignment does not appear to be enforced -
new DataView(new ArrayBuffer(8)).setUint32(1, 255)
works fine.However, all new
ArrayBuffer
s created in JS appear to have their allocations aligned on 16 (at least on my Mac OS machine). So I wonder if a certain alignment allows optimal performance? Maybe, for example, reading a series of 4 xUint16
s is faster if buffer is aligned to at least 8?Concerning whether memory should be initialized, I assume it doesn't have to be, since NodeJS provides a facility for this
Buffer.allocUnsafe
.Either way, it'd be great if the requirements (or lack thereof) could be made explicit in the docs).
I couldn't find any comments in Node's source code which answer these questions, or I'd be making a PR for the docs, not opening an issue!
Beta Was this translation helpful? Give feedback.
All reactions