Performance comparison of PHP's own compression method

When saving some data to redis, if the amount of data is very large, it will undoubtedly take up too much server memory and affect server performance. At this time, we might as well compress first and then write to redis.

When reading the content, you can decompress it first and then use it. The compression method is provided by php, one is the bzcompress() method and the other is the gzcompress() method, so which one is better?

Let's test it, the following is the php code:

  1. <?php
  2. header('Content-Type:text/html; charset=utf-8');
  3. $input = file_get_contents('/tmp/debug.log');
  4. echo 'Content length:'.strlen($input);
  5. echo '<br/>';
  6. $start_time = microtime(TRUE);
  7. $input_compressed = bzcompress($input,6);
  8. echo 'after compressing,time interval:'.(microtime(TRUE)-$start_time).', length:', strlen($input_compressed).'<br/>';
  9. $input_uncompressed = bzdecompress($input_compressed);
  10. echo 'after uncompressing,length:'.strlen($input_uncompressed).'<br/>';
  11. $start_time = microtime(TRUE);
  12. $input_compressed = gzcompress($input,6);
  13. echo 'after compressing,time interval:'.(microtime(TRUE)-$start_time).', length:', strlen($input_compressed).'<br/>';
  14. $input_uncompressed = gzuncompress($input_compressed);
  15. echo 'after uncompressing,length:'.strlen($input_uncompressed).'<br/>';


After execution, the result is as follows, the debug.log file has 11M content:


Content Length: 11190138

after compressing,time interval:1.1139051914215, length:359866

after uncompressing,length:11190138

after compressing,time interval:0.19483304023743, length:872131

after uncompressing,length:11190138


It can be seen that bzcompress() takes more time to compress, and gzcompress is better.

But in terms of compression effect, bzcompress() will be better, because there is less content after compression.

Related: Performance comparison of PHP's own compression method