Buffer.allocUnsafe(size)


  • size <integer> 新的 Buffer 所需的长度。

分配 size 个字节的新 Buffer。 如果 size 大于 buffer.constants.MAX_LENGTH 或小于 0,则抛出 ERR_INVALID_OPT_VALUE

以这种方式创建的 Buffer 实例的底层内存不会被初始化。 新创建的 Buffer 的内容是未知的,可能包含敏感的数据。 使用 Buffer.alloc() 来用零初始化 Buffer 实例。

const buf = Buffer.allocUnsafe(10);

console.log(buf);
// 打印(内容可能会有所不同): <Buffer a0 8b 28 3f 01 00 00 00 50 32>

buf.fill(0);

console.log(buf);
// 打印: <Buffer 00 00 00 00 00 00 00 00 00 00>

如果 size 不是数值,则会抛出 TypeError

Buffer 模块预先分配了大小为 Buffer.poolSize 的内部 Buffer 实例作为池,用于快速分配使用 Buffer.allocUnsafe()Buffer.from(array)Buffer.concat() 创建的新 Buffer 实例,仅当 size 小于或等于 Buffer.poolSize >> 1Buffer.poolSize 除以二再向下取整)时才使用弃用的 new Buffer(size) 构造函数。

使用此预先分配的内部内存池是调用 Buffer.alloc(size, fill) 与调用 Buffer.alloc(size, fill) 之间的关键区别。 具体来说,Buffer.alloc(size, fill) 永远不会使用内部 Buffer 池,而 Buffer.allocUnsafe(size).fill(fill) 会在 size 小于或等于 Buffer.poolSize 的一半时使用内部 Buffer 池。 当应用程序需要 Buffer.allocUnsafe() 提供的额外性能时,差异很细微,但可能很重要。

  • size <integer> The desired length of the new Buffer.

Allocates a new Buffer of size bytes. If size is larger than buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE is thrown.

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.

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>

A TypeError will be thrown if size is not a number.

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.concat(), and the deprecated new Buffer(size) constructor only when size is less than or equal to Buffer.poolSize >> 1 (floor of Buffer.poolSize divided by two).

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.