top of page

What is Data Compression?

Oct 24
12 min read
What is Data Compression?

 

Data compression represents information using fewer bits, reducing the data that needs to be stored or transferred when the input is suitable. Lossless compression lets a decoder reconstruct the original input exactly. Lossy compression discards selected information to achieve a smaller representation, so exact recovery is not possible from that representation alone.

 

The important qualification is that compression does not always make a file smaller, and a smaller file does not always arrive sooner. The result depends on the data, the encoding method, the processing cost and the link carrying it.

 

For a UK household uploading a NAS backup or downloading a web page, this is a question about how many bytes the application needs to move. It is separate from the capacity of the broadband connection. Our networking terminology guide connects this topic to the other layers involved.

 

How does data compression work?

 

A compressed representation contains instructions or codes that a compatible decoder can interpret. The decoder needs the format rules and, in some systems, additional shared information such as a dictionary. A smaller output is useful only if the receiver can reconstruct the information it needs.

 

Repetition and shorter codes

 

Imagine a log in which the same field names, device names and status messages occur thousands of times. A compressor can replace repeated sequences with references to data already seen, instead of writing every occurrence in full. Another technique gives frequently occurring symbols shorter codes and less frequent symbols longer codes.

 

DEFLATE combines LZ77-style repeated-string references with Huffman coding. The original DEFLATE specification, published as Informational RFC 1951 in May 1996, explains both mechanisms. These are examples of compression techniques, rather than a description of every codec.

 

A reference has its own cost. The encoder also needs framing and information that allows the decoder to interpret the stream. If patterns are scarce, or the input is very small, those costs can outweigh the savings.

 

What lossy encoding changes

 

Lossy media encoding can reduce precision or discard information that the chosen encoding process treats as less important. In common photographic JPEG encoding, image values are transformed and quantised: rounding the transformed values removes information that cannot subsequently be recovered exactly.

 

A useful result depends on the intended use. A smaller photograph may be acceptable for a web preview while being unsuitable as the only master for later editing. A lossy recording can sound acceptable without being identical to the original samples. File size and perceptual quality are different measurements.

 

Lossless versus lossy compression

 

Question

Lossless

Lossy

Can the decoder restore the input data exactly?

Yes, with a valid stream and the required decoder information

Generally no, because information was discarded

Typical uses

Documents, software, databases, logs and exact backup content

Photographs, audio and video where a quality trade-off is acceptable

Main trade-off

Size, encode/decode work, memory and compatibility

Those trade-offs plus irreversible information loss

What should be verified?

Restored bytes or the relevant lossless data representation

Visual/audio suitability as well as size and compatibility

 

The phrase “original data” needs a boundary. A lossless PNG can preserve decoded image pixel values while a conversion discards metadata or changes the encoded file bytes. Archiving an original image file losslessly preserves that file's bytes; re-exporting its pixels into another image format is a different operation.

 

Likewise, a format family can support several modes. Common JPEG photographs use lossy encoding, but JPEG specifications also include lossless processes. A file extension alone is not a complete description of how the data was encoded.

 

Data compression infographic explaining patterns, lossless restoration, lossy information removal, fewer bytes, processing costs and testing size, speed and quality

 

Why some files barely compress, or become larger

 

No lossless compressor can turn every possible input into a shorter output. There are fewer short bit strings than long ones, so there cannot be a unique shorter representation for every possible original. A scheme that shortens many useful inputs must leave some others unchanged or make them longer.

 

Already-compressed photographs, videos and archives have often had much of their useful redundancy removed. Compressing them again may save little, do nothing useful or increase the size. A mixed archive can still contain other members that compress well, so “already compressed” is not a guarantee about every byte in a folder.

 

Properly encrypted data is designed to conceal exploitable patterns and normally offers little useful compression. Compression and encryption solve different problems: reducing a representation does not make its contents confidential, and random-looking test data is not evidence of encryption strength.

 

Tiny inputs also have a practical disadvantage. A file header, trailer and encoding overhead can be larger than the saving available from a few bytes of content.

 

Original test: four inputs through gzip

 

We ran an in-memory experiment using Python 3.12.14 and zlib 1.3.2. The table shows gzip level 6 with modification time explicitly set to zero. Every output was decompressed and compared byte for byte with its corresponding input; SHA-256 comparisons also matched.

 

These are controlled synthetic examples, not a representative survey of household files or a prediction of your backup ratio. One MiB here means 1,048,576 bytes.

 

Input

Input bytes

gzip output bytes

Size change

Repeated synthetic log-like bytes

1,048,576

3,141

99.70% smaller

Seeded pseudorandom bytes

1,048,576

1,048,914

338 bytes larger

The gzip output of those pseudorandom bytes

1,048,914

1,049,252

338 bytes larger

Six-byte text: hello followed by a newline

6

26

20 bytes larger

 

The first input repeats the same short log-like pattern. It is deliberately extremely compressible and should not be presented as a typical log collection. The pseudorandom input used a fixed seed for repeatability; it was not a sample of encrypted traffic.

 

For the already-compressed row, decoding the outer gzip stream restores the inner gzip bytes. A second decoding would be needed to obtain the underlying pseudorandom bytes. “Restored exactly” always refers to the input to that particular encoding operation.

 

Does a higher compression level always help?

 

On the repeated input, gzip level 1 produced 6,194 bytes, while levels 6 and 9 both produced 3,141 bytes. A higher setting did not improve the output beyond level 6 in this case. Compression settings can change the effort spent searching for a better representation without guaranteeing a smaller result for every input.

 

We tested all four inputs at levels 1, 6 and 9. We did not measure CPU time, energy use or network throughput, so these observations cannot establish which level is fastest or best for your hardware.

 

A small reproducible example

 

This example compresses synthetic bytes in memory and verifies the result. It does not modify a file on disk. The Python gzip documentation describes the API and its version-specific behaviour.

 

import gzip
pattern = b'{"device":"nas-01","event":"backup_complete","status":"ok"}\n'size = 1_048_576original = (pattern * (size // len(pattern) + 1))[:size]encoded = gzip.compress(original, compresslevel=6, mtime=0)restored = gzip.decompress(encoded)assert restored == originalprint(len(original), len(encoded))

 

Our recorded result was 1,048,576 input bytes and 3,141 encoded bytes. Encoded output can differ across software versions or builds even when decoding restores the same original. Repeating the encoding with the same build and settings produced the same bytes in this experiment.

 

Original image test: size is not the same as preservation

 

We also encoded a synthetic 256 by 256 RGB raster using Pillow 12.3.0 and libjpeg-turbo 3.1.4.1. Its decoded RGB data occupied 196,608 bytes before file encoding. The pattern was generated mathematically rather than taken from a photograph.

 

For JPEG we used 4:4:4 sampling, with optimisation and progressive encoding disabled. PNG used compression level 6. We decoded each file back to RGB and compared the resulting pixel values with the source raster.

 

Encoding of the same synthetic raster

Encoded file bytes

Decoded RGB values exactly preserved?

PNG, compression level 6

10,534

Yes

JPEG, quality setting 90

62,839

No

JPEG, quality setting 50

23,626

No

 

PNG was smaller than either JPEG in this particular pattern. That is not a general ranking for photographs: content and encoder settings matter. The result demonstrates why choosing an encoder solely from a file extension or an assumed size hierarchy can mislead.

 

In our decoded comparisons, 65,526 of the 65,536 pixels changed at JPEG setting 90, and all 65,536 changed at setting 50. That count is an exact-value comparison, not a perceptual quality score. A JPEG quality setting of 90 does not mean that 90% of the original information was retained.

 

PNG restored the RGB values in this test. We did not test preservation of camera metadata, colour-management workflows or the byte identity of an original image file. Those require separate checks.

 

Algorithms, compressed streams and archives are different things

 

A codec describes encoding and decoding. A wrapper or container carries data and associated structure. An archive can package multiple named files. These roles can be combined, but they should not be confused.

 

Name

Role

Practical distinction

DEFLATE

Lossless compression format

Used within other formats, including common gzip and ZIP arrangements

gzip

Compressed-stream format

Adds framing and an integrity check around compressed data; not a directory archive by itself

tar plus gzip

Archiving followed by compression

tar packages files and metadata into a stream, then gzip compresses that stream

ZIP

Archive container

Members can use supported compression methods or be stored without compression

Brotli and Zstandard

Lossless compression formats

Different design choices, settings and decoder requirements; neither is a universal winner

PNG and common JPEG image encoding

Image formats with different encoding processes

Lossless pixel preservation and lossy size/quality choices need different verification

 

Brotli is described in RFC 7932 and Zstandard in RFC 8878. Choosing between implementations involves content, encoding cost, decoding cost, memory limits and receiver support. Some compression systems can use a dictionary that must also be available to the decoder; the compressed bytes are not necessarily self-sufficient in every configuration.

 

A higher compression setting can be sensible for a web asset encoded once and served many times. A live stream or an interactive transfer has a different budget because time spent encoding can delay delivery. Measure the actual application rather than assuming the smallest stored file is the best operational choice.

 

How to calculate compression ratio and space saving

 

State which definition you use, because tools can report ratios in different ways. Here, compression ratio means original size divided by compressed size. Space saving means the fraction of the original size removed.

 

For a clearly hypothetical 100 MB input compressed to 40 MB, the ratio is 100 divided by 40, or 2.5:1. The output is 40% of the original size and the space saving is 60%. A 2.5:1 ratio does not mean a 250% reduction.

 

Both sizes in that example are decimal: 100 MB is 100,000,000 bytes. Network rates are normally expressed in bits per second, so multiply bytes by eight when calculating a transfer duration. Keep MB and MiB separate rather than silently mixing them.

 

Does compression make a broadband transfer faster?

 

It can reduce the number of payload bytes crossing a bottleneck. It cannot increase the physical capacity of the connection. Our explanation of bandwidth separates that capacity from the work an application gets done.

 

A simple sequential model is: uncompressed time equals original bytes multiplied by eight, divided by payload bit rate. Compressed time equals encoding time, plus compressed bytes multiplied by eight divided by payload bit rate, plus decoding time.

 

For the hypothetical 100 MB to 40 MB example, assume encoding takes 2 seconds and decoding takes 0.5 seconds. These processing times and the compression result are assumptions, not measured codec performance. Assume a constant file-payload rate and no overlap between the stages.

 

Assumed file-payload rate

Uncompressed transfer

Compressed transfer plus processing

Result in this model

20 Mbit/s

40 seconds

16 + 2 + 0.5 = 18.5 seconds

21.5 seconds sooner

1 Gbit/s

0.8 seconds

0.32 + 2 + 0.5 = 2.82 seconds

2.02 seconds later

 

The same size reduction helps in the slower-link example but loses overall in the faster-link example because the assumed processing cost dominates. Actual streaming pipelines may overlap encoding, transfer and decoding. Precompressed downloads may have no encoding work on the user's critical path. Storage performance, protocol overhead, contention and retransmissions can change the outcome too.

 

UK home uploads, backups and streaming

 

For a household sending a NAS backup to remote storage, the upstream path may be the limiting resource even when downloads feel fast. Measure the relevant upload speed and the backup application's elapsed time rather than applying a download headline to an upload calculation. An FTTP connection still has application, CPU and storage limits.

 

Compression may help logs and other redundant backup content. It may add work with little benefit to a library dominated by encoded video or compressed photographs. If the backup system already compresses or encrypts its stored chunks, an extra archive layer needs testing rather than automatic acceptance.

 

Deduplication avoids storing repeated content across items or versions. Delta transfer reuses data already present at the destination. Compression encodes a representation more compactly. A backup or rsync workflow may combine techniques, but reduced transferred data does not prove that compression alone caused the saving.

 

Media streaming also trades bitrate against quality, encoding effort and latency. A lower bitrate does not guarantee the same perceived quality, and it does not eliminate congestion or WiFi loss. The codec and settings used by an application matter as much as the access connection.

 

How web compression works

 

HTTP can carry a compressed representation of a resource, such as HTML, CSS or JSON. A client advertises acceptable content codings with Accept-Encoding. If the server sends a gzip-coded representation, Content-Encoding tells the recipient how it was encoded. Content-Type still identifies the underlying media type.

 

The HTTP Semantics standard, RFC 9110, defines this negotiation and the Vary response field. When a server selects a representation according to Accept-Encoding, Vary: Accept-Encoding tells a cache that this request field affects selection.

 

This is an illustrative request and response header extract, not a capture from a tested server:

 

Request:Accept-Encoding: gzip, br
Response:Content-Type: text/html; charset=utf-8Content-Encoding: gzipVary: Accept-Encoding

 

It does not mean every request receives compression, or that every cache configuration is correct. A server can choose an uncompressed representation where appropriate. A JPEG's intrinsic image encoding is also different from an additional HTTP content coding; it is not automatically declared as Content-Encoding simply because the file is compressed internally.

 

Browser tools may show transferred size separately from decoded resource size. A decoded page larger than the network payload is therefore not inherently a fault. HTTP content coding, transport encryption and the broadband access link perform different jobs.

 

Integrity, safety and keeping usable originals

 

Compression is not encryption, authentication or backup retention. A successful extraction does not establish who created a file, whether its contents are safe or whether you can recover an older version after an unwanted overwrite.

 

The gzip format carries a CRC32 check for the uncompressed data. In our additional tests, an altered CRC field caused a BadGzipFile error and a truncated stream caused EOFError. Those two observations show error handling for those specific malformed inputs; they do not prove that every possible corruption or malicious change will be detected.

 

A checksum can help verify an expected result, but its algorithm and the trustworthiness of the reference both matter. For lossless backups, check restored content and test recovery. For lossy media, retain the original when later editing or exact preservation matters; recompressing a lossy file cannot recreate information already discarded.

 

Untrusted compressed input can expand to a very large output or demand excessive decoder memory and processing. Apply output-size, memory and time limits where the application supports them, and extract archives into a controlled location. A small download is not proof of a small resource requirement after decoding.

 

How to choose and test compression sensibly

 

Useful decisions start with the purpose of the data:

 

  • Preserve software, records and exact backup content with a lossless process and a tested restore path.

  • Choose lossy media settings only when the quality trade-off suits the intended viewing or listening use.

  • Check that the receiver supports the format, settings and any required dictionary.

  • Keep originals or recovery versions where a conversion or overwrite would be costly to reverse.

 

Then test a representative sample through the whole workflow:

 

  1. Identify the actual bottleneck: network transfer, storage, encoding, decoding or application behaviour.

  2. Record input size and content types, including files that are already compressed.

  3. Compare a small number of supported methods or settings on the same sample.

  4. Measure output size and complete elapsed time, including encode and decode work where it affects the user.

  5. Verify restored bytes for lossless data, or assess appropriate image/audio/video quality for lossy output.

  6. Test receiver compatibility, error handling and recovery before replacing an established workflow.

 

Do not select a production setting from our repeated-pattern result alone. Your real file mix, devices and transfer path can produce a very different balance.

 

Troubleshooting compression results

 

Symptom

Likely explanation to investigate

Useful next check

Archive is barely smaller or grows

Already-compressed, random-looking or tiny content; container overhead

Compare file types and test a representative subset without another compression layer

Smaller file takes longer overall

Encoding/decoding or storage cost outweighs transfer saving

Measure each stage and the complete elapsed time

Receiver cannot open the output

Unsupported format/method, missing dictionary, damaged or incomplete data

Confirm decoder requirements and transfer completeness; keep the original

Decompression reports an error

Truncation, corruption or another format problem

Obtain a known-good copy and verify against a trusted reference

Image looks worse after conversion

Lossy processing or unsuitable settings/workflow

Compare decoded output at its intended use size and return to the retained original

Memory use or decoded size is excessive

Large expansion or decoder-window/resource requirements

Stop uncontrolled extraction and use supported resource limits

 

Key takeaway

 

Data compression changes how information is represented. Lossless methods preserve the input data exactly; lossy methods trade information for a smaller result. The useful setting is the one that meets your preservation, compatibility, resource and end-to-end performance needs, demonstrated on your data rather than assumed from a headline ratio.

 

Frequently asked questions

 

What is data compression in simple terms?

 

Data compression represents information using fewer bits when the data is suitable. Lossless compression allows exact reconstruction of its input; lossy compression discards selected information and cannot restore it exactly from the compressed representation alone.

 

Does compression always make a file smaller?

 

No. Already-compressed data, random-looking bytes and very small inputs may gain little or become larger because the compressed representation has overhead. No lossless compressor can make every possible input shorter.

 

What is the difference between lossless and lossy compression?

 

Lossless compression lets a valid stream be decoded back to its original input data exactly. Lossy compression removes information, so the decoded result can be useful or look similar without being identical to the original.

 

Does compression increase broadband speed?

 

Compression can reduce the payload bytes that need to cross a connection, but it does not increase the connection's capacity. Whether a task finishes sooner depends on the size saving, encoding and decoding cost, and the rest of the transfer path.

 

Is a ZIP file always smaller than the original files?

 

No. ZIP is an archive container that can hold compressed or stored members. Its size depends on the contents, selected methods and archive overhead; already-compressed or tiny inputs may not become smaller.

 

Is compressed data encrypted?

 

Compression alone does not encrypt data. Encryption protects confidentiality, while compression changes representation to reduce size where possible. An application can combine them, but a compressed file is not automatically private or authenticated.

 
 
UK Techie Broadband Providers
bottom of page