线程池使用和性能注意事项


【Threadpool usage and performance considerations】

除了那些明确为同步的 API 之外,所有 zlib API 都使用 Node.js 内部线程池。这在某些应用中可能会导致意想不到的效果和性能限制。

【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.】

同时创建和使用大量 zlib 对象可能导致显著的内存碎片化。

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

import zlib from 'node:zlib';
import { Buffer } from 'node:buffer';

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) => {});
}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) => {});
}

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

【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.】