静态方法: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.