静态方法:Buffer.allocUnsafeSlow(size)


【Static method: Buffer.allocUnsafeSlow(size)

分配一个大小为 size 字节的新 Buffer。如果 size 大于 buffer.constants.MAX_LENGTH 或小于 0,则会抛出 ERR_OUT_OF_RANGE。如果 size 为 0,则会创建一个长度为零的 Buffer

【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. A zero-length Buffer is created if size is 0.】

以这种方式创建的 Buffer 实例的底层内存未初始化。新创建的 Buffer 的内容未知,可能包含敏感数据。使用 buf.fill(0) 将这些 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 buf.fill(0) to initialize such Buffer instances with zeroes.】

在使用 Buffer.allocUnsafe() 分配新的 Buffer 实例时,小于 Buffer.poolSize >>> 1(当使用默认 poolSize 时为 4KiB)的分配将从单个预分配的 Buffer 中切片。这使得应用可以避免创建许多单独分配的 Buffer 实例所带来的垃圾回收开销。这种方法通过无需跟踪和清理这么多单独的 ArrayBuffer 对象,从而提高了性能和内存使用效率。

【When using Buffer.allocUnsafe() to allocate new Buffer instances, allocations less than Buffer.poolSize >>> 1 (4KiB when default poolSize is used) are sliced from a single pre-allocated Buffer. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffer instances. This approach improves both performance and memory usage by eliminating the need to track and clean up as many individual ArrayBuffer objects.】

然而,在开发者可能需要从内存池中保留一小块内存且时间不确定的情况下,使用 Buffer.allocUnsafeSlow() 创建一个非池化的 Buffer 实例,然后复制出相关部分,可能是合适的做法。

【However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() and then copying out the relevant bits.】

import { Buffer } from 'node:buffer';

// Need to keep around a few small chunks of memory.
const store = [];

socket.on('readable', () => {
  let data;
  while (null !== (data = readable.read())) {
    // Allocate for retained data.
    const sb = Buffer.allocUnsafeSlow(10);

    // Copy the data into the new allocation.
    data.copy(sb, 0, 0, 10);

    store.push(sb);
  }
});const { Buffer } = require('node:buffer');

// Need to keep around a few small chunks of memory.
const store = [];

socket.on('readable', () => {
  let data;
  while (null !== (data = readable.read())) {
    // Allocate for retained data.
    const sb = Buffer.allocUnsafeSlow(10);

    // Copy the data into the new allocation.
    data.copy(sb, 0, 0, 10);

    store.push(sb);
  }
});

如果 size 不是数字,将会抛出 TypeError

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