← 中文资源

简体中文版本

Buffer.alloc 清零而 allocUnsafe 不清零

Buffer.alloc 把每个字节清零,可安全交给加密或网络;allocUnsafe 跳过清零更快,但复用池内存,出函数前必须逐字节覆写。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

alloc:        [ 0, 0, 0, 0 ]
allocUnsafe:  [ 120, 86, 52, 18 ]
lengths:      4 4
filled? true

实现说明

safe、fast 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 跑完文件,输出里会留下标记——alloc:、allocUnsafe:、lengths:。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 文件用顶层绑定保存自己的状态:safe、fast。

核心语句

const fast = Buffer.allocUnsafe(4);
fast.writeUInt32LE(0x12345678);
const safe = Buffer.alloc(4);

代码示例

// Buffer.alloc zero-fills every byte, so stale memory from a
// previous write can never leak into what you hand to crypto, the
// network, or a response body
const safe = Buffer.alloc(4);
console.log('alloc:       ', [...safe]);

// Buffer.allocUnsafe skips the zero-fill for speed. Its bytes hold
// whatever the shared pool last wrote there — every byte must be
// overwritten before the buffer leaves your code
const fast = Buffer.allocUnsafe(4);
fast.writeUInt32LE(0x12345678);
console.log('allocUnsafe: ', [...fast]);

// Same length, same type — only the initial contents differ
console.log('lengths:     ', safe.length, fast.length);
console.log('filled?', fast.readUInt32LE(0) === 0x12345678);