实现说明
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);