Belajar
← All lessons

How gzip compression works

literalback-reference (distance, length)

Squeeze your own text

Text
What gzip writes

original
LZ77
real gzip

lz77.js

function lz77(text) {  const out = [];  let i = 0;  while (i < text.length) {    const { dist, len } = longestMatch(text, i);    if (len >= 3) {      out.push({ dist, len }); // go back, copy      i += len;    } else {      out.push(text[i]);       // just the letter      i += 1;    }  }  return out;}

gzip.js

// the real thing, built into the browserconst stream = new Blob([text]).stream()  .pipeThrough(new CompressionStream("gzip"));const gz = await new Response(stream).arrayBuffer();

Finding one match in the sliding window

encode.js

function longestMatch(text, i) {  let best = { dist: 0, len: 0 };  for (let j = Math.max(0, i - 32768); j < i; j++) {    let len = 0;    while (text[j + len] === text[i + len]) len++;    if (len > best.len) best = { dist: i - j, len };  }  return best;} const m = longestMatch(text, i);if (m.len < 3) out.push(text[i]);else out.push(m);

decode.js

let out = "";for (const t of tokens) {  if (typeof t === "string") out += t;  else for (let k = 0; k < t.len; k++)    out += out[out.length - t.dist];}

Some data won't shrink no repeats, nothing to point back to

Gzip thisHTML pageRandom bytesGzipped again
First bytes

before
after

JPEG, PNG, MP4 and zip files are already compressed, so servers skip gzip for them

sizes.js

const page = renderHtml(products);const noise = crypto.getRandomValues(new Uint8Array(page.length));const packed = await gzip(page); await gzip(page);   // shrinks: tags and words repeatawait gzip(noise);  // grows: no repeats to point back toawait gzip(packed); // grows: the repeats are already gone

Browser and server agree on gzip with two headers

Browser
shop.test

browser.js

// the browser adds Accept-Encoding for youconst res = await fetch("/");// and unzips the body before you read itconst html = await res.text();

server.js

app.get("/", (req, res) => {  const page = render("index.html");  const accepts = req.headers["accept-encoding"] ?? "";  if (accepts.includes("gzip")) {    res.setHeader("Content-Encoding", "gzip");    res.setHeader("Vary", "Accept-Encoding");    return res.send(zlib.gzipSync(page));  }  res.send(page);});

Topics

Next: How CORS works

Open lesson