对于基于 zlib 的流


zlib/zconf.h 开始,针对 Node.js 使用进行了修改:

deflate 的内存要求是(以字节为单位):

(1 << (windowBits + 2)) + (1 << (memLevel + 9))

即:windowBits 的 128K = 15 + memLevel 的 128K = 8(默认值)加上小对象的几千字节。

例如,要将默认内存要求从 256K 减少到 128K,应将选项设置为:

const options = { windowBits: 14, memLevel: 7 };

然而,这通常会降低压缩性能。

inflate 的内存要求是(以字节为单位)1 << windowBits。 也就是说,windowBits 的 32K = 15(默认值)加上小对象的几千字节。

这是对大小为 chunkSize 的单个内部输出平板缓冲区的补充,默认为 16K。

zlib 压缩的速度受 level 设置的影响最大。 更高的级别将导致更好的压缩,但需要更长的时间才能完成。 较低的级别将导致较少的压缩,但会更快。

一般来说,更大的内存使用选项意味着 Node.js 必须对 zlib 进行更少的调用,因为它能够在每个 write 操作上处理更多的数据。 所以,这是影响速度的另一个因素,以内存使用为代价。

From zlib/zconf.h, modified for Node.js usage:

The memory requirements for deflate are (in bytes):

(1 << (windowBits + 2)) + (1 << (memLevel + 9))

That is: 128K for windowBits = 15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects.

For example, to reduce the default memory requirements from 256K to 128K, the options should be set to:

const options = { windowBits: 14, memLevel: 7 };

This will, however, generally degrade compression.

The memory requirements for inflate are (in bytes) 1 << windowBits. That is, 32K for windowBits = 15 (default value) plus a few kilobytes for small objects.

This is in addition to a single internal output slab buffer of size chunkSize, which defaults to 16K.

The speed of zlib compression is affected most dramatically by the level setting. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster.

In general, greater memory usage options will mean that Node.js has to make fewer calls to zlib because it will be able to process more data on each write operation. So, this is another factor that affects the speed, at the cost of memory usage.