静态方法:Buffer.allocUnsafe(size)
【Static method: Buffer.allocUnsafe(size)】
分配一个大小为 size 字节的新 Buffer。如果 size 大于 buffer.constants.MAX_LENGTH 或小于 0,将抛出 ERR_OUT_OF_RANGE。
【Allocates a new Buffer of size bytes. If size is larger than
buffer.constants.MAX_LENGTH or smaller than 0, ERR_OUT_OF_RANGE
is thrown.】
以这种方式创建的 Buffer 实例的底层内存未初始化。新创建的 Buffer 的内容未知,可能包含敏感数据。使用 Buffer.alloc() 来初始化 Buffer 实例并填充零值。
【The underlying memory for Buffer instances created in this way is not
initialized. The contents of the newly created Buffer are unknown and
may contain sensitive data. Use Buffer.alloc() instead to initialize
Buffer instances with zeroes.】
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(10);
console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(10);
console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>如果 size 不是数字,将会抛出 TypeError。
【A TypeError will be thrown if size is not a number.】
Buffer 模块预先分配了一个大小为 Buffer.poolSize 的内部 Buffer 实例,该实例用作快速分配新 Buffer 实例的池,这些实例仅在使用 Buffer.allocUnsafe()、Buffer.from(array)、Buffer.from(string) 和 Buffer.concat() 创建时,并且当 size 小于 Buffer.poolSize >>> 1(Buffer.poolSize 除以二的下取整)时才使用。
【The Buffer module pre-allocates an internal Buffer instance of
size Buffer.poolSize that is used as a pool for the fast allocation of new
Buffer instances created using Buffer.allocUnsafe(), Buffer.from(array),
Buffer.from(string), and Buffer.concat() only when size is less than
Buffer.poolSize >>> 1 (floor of Buffer.poolSize divided by two).】
使用这个预分配的内部内存池是调用 Buffer.alloc(size, fill) 与 Buffer.allocUnsafe(size).fill(fill) 之间的关键区别。具体来说,Buffer.alloc(size, fill) 永远不会使用内部的 Buffer 池,而 Buffer.allocUnsafe(size).fill(fill) 如果 size 小于或等于 Buffer.poolSize 的一半,则会使用内部 Buffer 池。这种差异很微妙,但当应用需要 Buffer.allocUnsafe() 提供的额外性能时可能很重要。
【Use of this pre-allocated internal memory pool is a key difference between
calling Buffer.alloc(size, fill) vs. Buffer.allocUnsafe(size).fill(fill).
Specifically, Buffer.alloc(size, fill) will never use the internal Buffer
pool, while Buffer.allocUnsafe(size).fill(fill) will use the internal
Buffer pool if size is less than or equal to half Buffer.poolSize. The
difference is subtle but can be important when an application requires the
additional performance that Buffer.allocUnsafe() provides.】