静态方法: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 实例,该实例仅当 size 小于 Buffer.poolSize >>> 1Buffer.poolSize 的下限除以二)时才用作使用 Buffer.allocUnsafe()Buffer.from(array)Buffer.from(string)Buffer.concat() 创建的新 Buffer 实例的快速分配池。

¥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.alloc(size, fill) 之间的关键区别。具体来说,Buffer.alloc(size, fill) 永远不会使用内部 Buffer 池,而如果 size 小于或等于 Buffer.poolSize 的一半,Buffer.allocUnsafe(size).fill(fill) 将使用内部 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.