CodePark/ questions / Buffers & binary data
START PRACTICINGPRACTICE
Backend question · Node.js › Buffers & binary data

What is the difference between Buffer.alloc(size) and Buffer.allocUnsafe(size)?

alloc fills the memory with zeros; allocUnsafe skips that, so it is faster but may contain old data from memory

alloc fills the memory with zeros. allocUnsafe skips that step, so it is faster. But it returns uninitialized memory, which can hold leftover bytes from earlier allocations, such as secrets. You must overwrite it fully before you read it or send it.

"
allocUnsafe can grow beyond its size; alloc cannot" is wrong: neither buffer can grow.

"They are identical;
allocUnsafe is just a deprecated alias" is also wrong. The truly deprecated API is new Buffer(size). In old Node versions, it behaved like allocUnsafe and caused security bugs.