我在nginx 1.3.9下用两个文件进行了测试,这些是我在各个级别上获得的结果:
text/html
-phpinfo():
0 55.38 KiB (100.00% of original size)
1 11.22 KiB ( 20.26% of original size)
2 10.89 KiB ( 19.66% of original size)
3 10.60 KiB ( 19.14% of original size)
4 10.17 KiB ( 18.36% of original size)
5 9.79 KiB ( 17.68% of original size)
6 9.62 KiB ( 17.37% of original size)
7 9.50 KiB ( 17.15% of original size)
8 9.45 KiB ( 17.06% of original size)
9 9.44 KiB ( 17.05% of original size)
application/x-javascript
-jQuery 1.8.3(未压缩):
0 261.46 KiB (100.00% of original size)
1 95.01 KiB ( 36.34% of original size)
2 90.60 KiB ( 34.65% of original size)
3 87.16 KiB ( 33.36% of original size)
4 81.89 KiB ( 31.32% of original size)
5 79.33 KiB ( 30.34% of original size)
6 78.04 KiB ( 29.85% of original size)
7 77.85 KiB ( 29.78% of original size)
8 77.74 KiB ( 29.73% of original size)
9 77.75 KiB ( 29.74% of original size)
我不确定这有多大代表性,但应作为示例。另外,我没有考虑CPU使用率,但是从这些结果来看,理想的压缩级别似乎在4
和之间6
。
此外,如果使用gzip_static
模块,则可能需要预压缩文件(在PHP中):
function gzip_static($path)
{
if ((extension_loaded('zlib') === true) && (is_file($path) === true))
{
$levels = array();
$content = file_get_contents($path);
foreach (range(1, 9) as $level)
{
$levels[$level] = strlen(gzencode($content, $level));
}
if ((count($levels = array_filter($levels)) > 0) && (min($levels) < strlen($content)))
{
if (file_put_contents($path . '.gz', gzencode($content, array_search(min($levels), $levels)), LOCK_EX) !== false)
{
return touch($path . '.gz', filemtime($path), fileatime($path));
}
}
}
return false;
}
这样一来,您可以在不牺牲每个请求的CPU的情况下获得最佳压缩效果。