线程池的使用与性能的考虑


所有 zlib API,除了那些显式同步的 API,都使用 Node.js 内部线程池。 这可能会在某些应用程序中导致令人惊讶的效果和性能限制。

同时创建和使用大量压缩对象会导致显着的内存碎片。

const zlib = require('node:zlib');

const payload = Buffer.from('This is some data');

// 警告:不要这样做!
for (let i = 0; i < 30000; ++i) {
  zlib.deflate(payload, (err, buffer) => {});
}

在前面的示例中,同时创建了 30,000 个 deflate 实例。 由于某些操作系统如何处理内存分配和释放,这可能会导致严重的内存碎片。

强烈建议缓存压缩操作的结果以避免重复工作。

All zlib APIs, except those that are explicitly synchronous, use the Node.js internal threadpool. This can lead to surprising effects and performance limitations in some applications.

Creating and using a large number of zlib objects simultaneously can cause significant memory fragmentation.

const zlib = require('node:zlib');

const payload = Buffer.from('This is some data');

// WARNING: DO NOT DO THIS!
for (let i = 0; i < 30000; ++i) {
  zlib.deflate(payload, (err, buffer) => {});
}

In the preceding example, 30,000 deflate instances are created concurrently. Because of how some operating systems handle memory allocation and deallocation, this may lead to significant memory fragmentation.

It is strongly recommended that the results of compression operations be cached to avoid duplication of effort.