Node.js & Libuv•Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)
Buffers: `Buffer.alloc()` vs `Buffer.allocUnsafe()`.
In Simple Words: Buffers allocate raw binary memory outside the V8 heap in native C++ memory:
Buffer.alloc(size): Initializes memory and zeroes out all bytes. Safe against credential leaks.Buffer.allocUnsafe(size): Allocates raw uninitialized memory without zeroing it out. Faster, but exposes old sensitive memory remnants (passwords, tokens) to the application!
javascript
// Safe: initialized with 0s
const safeBuf = Buffer.alloc(10);
console.log(safeBuf); // <Buffer 00 00 00 00 00 00 00 00 00 00>
// Unsafe: may contain old leftover RAM bytes!
const unsafeBuf = Buffer.allocUnsafe(10);
console.log(unsafeBuf); // <Buffer e8 3a 4f ...>