node.js - Node.js 的最佳缓冲区大小?

标签 node.js memory-management buffer allocation

我有一种情况需要获取流并将其分块到缓冲区中。我计划编写一个对象转换流,它采用常规输入数据并输出 Buffer 对象(其中缓冲区的大小都相同)。也就是说,如果我的分块器转换配置为 8KB,并且写入了 4KB,它将等到另外写入 4KB,然后再输出一个 8KB 的 Buffer 实例。

我可以选择缓冲区的大小,只要它在 8KB 到 32KB 的范围内即可。是否有最佳尺寸可供选择?我很好奇的原因是 the Node.js documentation speaks of using SlowBuffer备份缓冲区,并分配至少 8KB 的空间:

In order to avoid the overhead of allocating many C++ Buffer objects for small blocks of memory in the lifetime of a server, Node allocates memory in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it will be backed by a parent SlowBuffer object. If it is larger than this, then Node will allocate a SlowBuffer slab for it directly.

这是否意味着 8KB 是一个有效的大小,如果我使用 12KB,就会分配两个 8KB 的 SlowBuffer?还是仅仅意味着最小的有效大小是 8KB?简单地使用 8KB 的倍数怎么样?或者,这根本不重要吗?

最佳答案

基本上是说,如果您的 Buffer 小于 8KB,它会尝试将其放入预先分配的 8KB 内存块中。它会一直将 Buffer 放入那个 8KB block 中,直到一个不适合为止,然后它会分配一个新的 8KB block 。如果 Buffer 大于 8KB,它将获得自己的内存分配。

您实际上可以通过查看缓冲区 here 的 Node 源来了解发生了什么:

if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
  if (this.length > poolSize - poolOffset)
    createPool();
  this.parent = sliceOnto(allocPool,
                          this,
                          poolOffset,
                          poolOffset + this.length);
  poolOffset += this.length;
} else {
  alloc(this, this.length);
}

看一下,它实际上看起来只会将小于或等于 4KB 的 Buffer 放入预分配的 block 中(Buffer.poolSize >>> 1Buffer.poolSize = 8 * 1024 时为 4096

至于根据您的情况选择最佳尺寸,我认为这取决于您最终使用它的目的。但是,一般来说,如果您想要一个小于或等于 8KB 的 block ,我会选择小于或等于 4KB 的 block ,这些 block 将均匀地适合该 8KB 预分配(4KB、2KB、1KB 等)。否则,大于 8KB 的 block 大小应该不会造成太大差异。

关于node.js - Node.js 的最佳缓冲区大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24522931/

相关文章:

javascript - 在 Meteor.js 中显示来自对象的 FS.File 引用

c - 使用结构进行动态内存分配

c++ - 数据管理错误 C++

node.js - 如何以express方式发送缓冲区数据?

javascript - 在 nodejs 中遇到 promise 问题

javascript - npm init 中的 --yes 参数是什么意思?

emacs - 如何在 Emacs 中保存我的迷你缓冲区历史记录?

linux - 比较缓冲区与 argv 错误

node.js - 从前端停止 Node 服务器中的功能

multithreading - 消费者生产者 : Pausing the consumer if memory usage goes beyond a particular threshold