论坛风格切换
  • 5448阅读
  • 2回复

PHP压缩函数效果比较实践之gzcompress/gzdeflate/gzencode [复制链接]

上一主题 下一主题
离线rickyleo
 

发帖
315
金币
0
威望
99
只看楼主 倒序阅读 使用道具 楼主  发表于: 2012-01-11
ThinkPHP提供了debug_start()和debug_end()函数,可以很清楚的看到之间的代码消耗的服务器内存资源和执行时间,为了将效果更加精确将消耗资源单位k改成字节。
网络上一篇文章被转载了N次,见 http://www.baidu.com/s?wd=gzencode+gzcompress&rsv_bp=0&rsv_spt=3&inputT=6328,说是gzdeflate压缩效果最好,gzcompress次之,gzencode最差,不过他们是通过strlen来获取长度的,不太确定这个strlen是否靠谱,所以本地测试了下。
我经过测试后结果表明 gzcompress比gzencode优秀,gzencode比gzdeflate优秀,又看ThinkPHP框架在写缓存前也是用gzcompress先进行压缩数据再保存的。测试结果如下:
  1. Process noCompress: Times 0.000044s Memories 1,024 Byte
  2. Process gzdeflate: Times 0.000129s Memories 832 Byte
  3. Process gzcompress: Times 0.000084s Memories 696 Byte
  4. Process gzencode: Times 0.000104s Memories 704 Byte

测试代码如下:
  1. <?php
  2. class TestAction extends Action{
  3.     public function index(){
  4.         debug_start('noCompress');
  5.         $str = "待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容";
  6.         debug_end('noCompress');
  7.         
  8.         debug_start('gzdeflate');
  9.         $str = gzdeflate("待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容", 9);
  10.         //gzinflate($data, $length);
  11.         debug_end('gzdeflate');
  12.         
  13.         debug_start('gzcompress');
  14.         $str = gzcompress("待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容", 9);
  15.         //gzuncompress($data, $length);
  16.         debug_end('gzcompress');
  17.         
  18.         debug_start('gzencode');
  19.         $str = gzencode("待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容待压缩内容", 9);
  20.         //gzdecode($data);
  21.         debug_end('gzencode');
  22.     }
  23. }
  24. if (!function_exists('gzdecode')) {
  25.     function gzdecode ($data) {
  26.         $flags = ord(substr($data, 3, 1));
  27.         $headerlen = 10;
  28.         $extralen = 0;
  29.         $filenamelen = 0;
  30.         if ($flags & 4) {
  31.             $extralen = unpack('v' ,substr($data, 10, 2));
  32.             $extralen = $extralen[1];
  33.             $headerlen += 2 + $extralen;
  34.         }
  35.         if ($flags & 8) // Filename
  36.             $headerlen = strpos($data, chr(0), $headerlen) + 1;
  37.         if ($flags & 16) // Comment
  38.             $headerlen = strpos($data, chr(0), $headerlen) + 1;
  39.         if ($flags & 2) // CRC at end of file
  40.             $headerlen += 2;
  41.         $unpacked = @gzinflate(substr($data, $headerlen));
  42.         if ($unpacked === FALSE)
  43.             $unpacked = $data;
  44.         return $unpacked;
  45.     }
  46. }
  47. ?>









1条评分金币+20
mgarfield 金币 +20 给你个好评哦亲~ 2012-01-12
离线mgarfield

发帖
520
金币
0
威望
62
只看该作者 沙发  发表于: 2012-01-12
给你个好评哦亲~
离线mgarfield

发帖
520
金币
0
威望
62
只看该作者 板凳  发表于: 2012-01-12
最好是在同一个index方法里测试一种压缩效果。时间获取函数可能没那么精确。
快速回复
限100 字节
批量上传需要先选择文件,再选择上传
 
提到某人:
选择好友
上一个 下一个