PHP Compression: gzcompress vs gzdeflate vs gzencode

Really, PHP? You have three different zlib functions for compressing? I’m sure there’s an excellent reason for this but I’ve barely looked at zlib in PHP ever so was a bit surprised at the variety and subtle differences between them.

I happened to pick gzcompress() initially and struggled a bit trying to figure out what was going on – it seems to produce a consistent two byte header of 78 5e, but that is different to what is mentioned in the magic number listing I found – gzip is listed as 1f 8b 08, which is what you’ll see if you use gzencode(). gzdeflate() doesn’t seem to leave a header at all.

This post on Stack Overflow has a little info about the differences; which one you’ll need depends exactly on what you’re doing.

To make things even more awesome though, just after I decided I want to use gzencode(), I discovered that gzdecode() isn’t actually implemented in PHP 5.3 – apparently it is scheduled for PHP 6, so presumably gzencode() is only useful to those who have another mechanism to extract gzip’ed data.

I did a very quick benchmark with about 30 files totaling around 130MB and got the following results using compression option 4, though I tested on 9 and there was little difference:

gzdeflate():

real 0m5.562s
user 0m5.436s
sys 0m0.125s

gzencode():
real 0m5.679s
user 0m5.566s
sys 0m0.111s

gzcompress():

real 0m6.011s
user 0m5.878s
sys 0m0.131s

One thought on “PHP Compression: gzcompress vs gzdeflate vs gzencode”

  1. Thank you so much for benchmarks. Things now have changed for PHP 7. gzcompress() is faster than gzencode(). For future readers if you want to compress strings go with gzcompress() otherwise go with the gzencode().

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.