Convert Figma logo to code with AI

facebook logozstd

Zstandard - Fast real-time compression algorithm

23,176
2,062
23,176
193

Top Related Projects

6,094

A fast compressor/decompressor

10,226

Extremely Fast Compression algorithm

13,454

Brotli compression format

5,575

A massively spiffy yet delicately unobtrusive compression library.

8,937

Extremely fast non-cryptographic hash algorithm

Optimized Go Compression Packages

Quick Overview

Zstandard (zstd) is a fast lossless compression algorithm developed by Facebook. It offers a high compression ratio while maintaining excellent compression and decompression speeds. Zstd is designed to be versatile, with a wide range of compression levels to suit various use cases.

Pros

  • Extremely fast compression and decompression speeds
  • High compression ratios, especially at higher levels
  • Flexible, with multiple compression levels and dictionary support
  • Cross-platform compatibility and wide language support

Cons

  • Newer format, so not as universally supported as older algorithms like gzip
  • Higher memory usage compared to some older compression algorithms
  • May not be ideal for very small files due to dictionary overhead

Code Examples

  1. Basic compression:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zstd.h>

int main(void) {
    const char* const srcStr = "Hello, Zstandard!";
    size_t const srcSize = strlen(srcStr);
    size_t const cBuffSize = ZSTD_compressBound(srcSize);
    void* const cBuff = malloc(cBuffSize);

    size_t const cSize = ZSTD_compress(cBuff, cBuffSize, srcStr, srcSize, 1);
    if (ZSTD_isError(cSize)) {
        fprintf(stderr, "Error compressing: %s\n", ZSTD_getErrorName(cSize));
        free(cBuff);
        return 1;
    }

    printf("Compressed from %zu to %zu bytes\n", srcSize, cSize);
    free(cBuff);
    return 0;
}
  1. Basic decompression:
#include <stdio.h>
#include <stdlib.h>
#include <zstd.h>

int main(void) {
    // Assume 'cBuff' contains compressed data and 'cSize' is its size
    size_t const rSize = ZSTD_getFrameContentSize(cBuff, cSize);
    void* const rBuff = malloc(rSize);

    size_t const dSize = ZSTD_decompress(rBuff, rSize, cBuff, cSize);
    if (ZSTD_isError(dSize)) {
        fprintf(stderr, "Error decompressing: %s\n", ZSTD_getErrorName(dSize));
        free(rBuff);
        return 1;
    }

    printf("Decompressed %zu bytes\n", dSize);
    free(rBuff);
    return 0;
}
  1. Streaming compression:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zstd.h>

int main(void) {
    const char* const srcStr = "Hello, Zstandard streaming!";
    size_t const srcSize = strlen(srcStr);
    
    ZSTD_CStream* const cstream = ZSTD_createCStream();
    if (cstream==NULL) { fprintf(stderr, "ZSTD_createCStream() error\n"); return 1; }
    
    size_t const initResult = ZSTD_initCStream(cstream, 1);
    if (ZSTD_isError(initResult)) {
        fprintf(stderr, "ZSTD_initCStream() error: %s\n", ZSTD_getErrorName(initResult));
        return 1;
    }

    ZSTD_outBuffer output = { malloc(ZSTD_compressBound(srcSize)), ZSTD_compressBound(srcSize), 0 };
    ZSTD_inBuffer input = { srcStr, srcSize, 0 };

    while (input.pos < input.size) {
        size_t const result = ZSTD_compressStream(cstream, &output, &input);
        if (ZSTD_isError(result

Competitor Comparisons

6,094

A fast compressor/decompressor

Pros of Snappy

  • Faster compression speed, especially for small data sizes
  • Lower memory usage during compression
  • Simpler implementation, easier to integrate into projects

Cons of Snappy

  • Lower compression ratio compared to Zstd
  • Lacks advanced features like dictionary compression
  • Not as actively maintained as Zstd

Code Comparison

Snappy:

char* output = new char[snappy::MaxCompressedLength(input_length)];
size_t output_length;
snappy::RawCompress(input, input_length, output, &output_length);

Zstd:

size_t const cBuffSize = ZSTD_compressBound(srcSize);
void* const cBuff = malloc(cBuffSize);
size_t const cSize = ZSTD_compress(cBuff, cBuffSize, srcBuffer, srcSize, 1);

Both libraries offer simple APIs for compression, but Zstd provides more options for fine-tuning compression levels and advanced features. Snappy's implementation is more straightforward, focusing on speed over compression ratio.

Zstd offers better overall performance and compression ratios, especially for larger datasets. It also provides more advanced features like dictionary compression and adjustable compression levels. However, Snappy may be preferred in scenarios where compression speed is critical and memory usage needs to be minimized.

10,226

Extremely Fast Compression algorithm

Pros of lz4

  • Extremely fast compression and decompression speeds
  • Simple and lightweight implementation
  • Lower memory usage during compression

Cons of lz4

  • Lower compression ratio compared to Zstd
  • Less suitable for archiving or long-term storage
  • Fewer advanced features and customization options

Code Comparison

lz4:

char* compressed = LZ4_compress_default(src, dst, srcSize, dstCapacity);
int decompressedSize = LZ4_decompress_safe(compressed, decompressed, compressedSize, maxDecompressedSize);

Zstd:

size_t compressedSize = ZSTD_compress(dst, dstCapacity, src, srcSize, 1);
size_t decompressedSize = ZSTD_decompress(decompressed, maxDecompressedSize, compressed, compressedSize);

Both libraries offer simple APIs for basic compression and decompression. Zstd provides more advanced options for fine-tuning compression levels and dictionary usage, while lz4 focuses on simplicity and speed.

lz4 is ideal for scenarios requiring extremely fast compression/decompression with moderate size reduction, such as real-time data transmission or in-memory compression. Zstd offers a better balance between compression ratio and speed, making it more suitable for a wider range of applications, including file compression and archiving.

13,454

Brotli compression format

Pros of Brotli

  • Generally achieves better compression ratios, especially for small files and web content
  • Widely supported by modern web browsers, making it ideal for web-based compression
  • Offers a dictionary-based compression approach, which can be beneficial for certain types of data

Cons of Brotli

  • Slower compression speed compared to Zstd, especially at higher compression levels
  • Less suitable for real-time compression scenarios due to its focus on compression ratio over speed
  • Limited support outside of web browsers compared to more versatile alternatives like Zstd

Code Comparison

Brotli compression example:

size_t output_size = BrotliEncoderMaxCompressedSize(input_size);
uint8_t* output = malloc(output_size);
BrotliEncoderCompress(quality, BROTLI_DEFAULT_WINDOW, BROTLI_DEFAULT_MODE,
                      input_size, input, &output_size, output);

Zstd compression example:

size_t const cBuffSize = ZSTD_compressBound(srcSize);
void* const cBuff = malloc(cBuffSize);
size_t const cSize = ZSTD_compress(cBuff, cBuffSize, src, srcSize, compressionLevel);

Both libraries offer simple APIs for compression, but Zstd's interface is slightly more straightforward. Brotli provides more fine-grained control over compression parameters, while Zstd focuses on simplicity and speed.

5,575

A massively spiffy yet delicately unobtrusive compression library.

Pros of zlib

  • Widely adopted and supported across many platforms and programming languages
  • Smaller library size, making it suitable for embedded systems and resource-constrained environments
  • Generally faster for small data sizes (< 10KB)

Cons of zlib

  • Lower compression ratio compared to Zstd, especially for larger files
  • Slower compression and decompression speeds for larger data sets
  • Less flexible in terms of compression level options and advanced features

Code Comparison

zlib:

z_stream strm;
deflateInit(&strm, Z_DEFAULT_COMPRESSION);
deflate(&strm, Z_FINISH);
deflateEnd(&strm);

Zstd:

size_t cSize = ZSTD_compress(cBuff, cBuffSize, src, srcSize, 1);
size_t dSize = ZSTD_decompress(rBuff, rBuffSize, cBuff, cSize);

Zstd offers a simpler API for basic compression and decompression tasks, while zlib requires more setup and cleanup code. However, zlib provides more fine-grained control over the compression process, which can be beneficial in certain scenarios.

Both libraries are well-maintained and actively developed, but Zstd is generally considered more modern and efficient for larger data sets. The choice between the two depends on specific project requirements, target platforms, and performance needs.

8,937

Extremely fast non-cryptographic hash algorithm

Pros of xxHash

  • Faster hash computation, especially for small inputs
  • Simpler implementation, easier to integrate into projects
  • Smaller codebase, making it more lightweight

Cons of xxHash

  • Limited to hashing functionality, lacks compression capabilities
  • Less actively maintained compared to zstd
  • Fewer language bindings and integrations available

Code Comparison

xxHash (hash computation):

XXH64_hash_t hash = XXH64(input, length, seed);

zstd (compression):

size_t compressedSize = ZSTD_compress(dst, dstCapacity, src, srcSize, compressionLevel);

Key Differences

  • Purpose: xxHash focuses on fast hashing, while zstd is primarily a compression library
  • Feature set: zstd offers a wider range of compression-related features
  • Performance: xxHash excels in hash speed, zstd in compression ratio and speed
  • Community: zstd has a larger user base and more frequent updates

Use Cases

xxHash is ideal for:

  • Checksumming
  • Hash tables
  • Content-based addressing

zstd is better suited for:

  • File and data compression
  • Network data transfer optimization
  • Storage space reduction

Both projects are open-source and provide C implementations, but zstd offers more language bindings and integrations with other tools and frameworks.

Optimized Go Compression Packages

Pros of compress

  • Written in Go, offering better integration with Go projects
  • Provides multiple compression algorithms (zstd, snappy, s2, deflate)
  • Active development with frequent updates and improvements

Cons of compress

  • Generally slower compression/decompression speeds compared to zstd
  • Less widespread adoption and ecosystem support
  • May have higher memory usage in some scenarios

Code Comparison

zstd (C):

size_t ZSTD_compress(void* dst, size_t dstCapacity,
                     const void* src, size_t srcSize,
                     int compressionLevel);

compress (Go):

func Encode(dst []byte, src []byte) ([]byte, error)
func Decode(dst []byte, src []byte) ([]byte, error)

Summary

zstd, developed by Facebook, is a C-based compression library known for its high compression ratio and speed. compress, on the other hand, is a Go-based library offering multiple compression algorithms, including a zstd implementation.

While compress provides better integration for Go projects and offers a variety of algorithms, zstd generally outperforms it in terms of speed and has wider adoption. The choice between the two depends on the specific project requirements, language preferences, and performance needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Zstandard

Zstandard, or zstd as short version, is a fast lossless compression algorithm, targeting real-time compression scenarios at zlib-level and better compression ratios. It's backed by a very fast entropy stage, provided by Huff0 and FSE library.

Zstandard's format is stable and documented in RFC8878. Multiple independent implementations are already available. This repository represents the reference implementation, provided as an open-source dual BSD OR GPLv2 licensed C library, and a command line utility producing and decoding .zst, .gz, .xz and .lz4 files. Should your project require another programming language, a list of known ports and bindings is provided on Zstandard homepage.

Development branch status:

Build Status Build status Build status Fuzzing Status

Benchmarks

For reference, several fast compression algorithms were tested and compared on a desktop featuring a Core i7-9700K CPU @ 4.9GHz and running Ubuntu 20.04 (Linux ubu20 5.15.0-101-generic), using lzbench, an open-source in-memory benchmark by @inikep compiled with gcc 9.4.0, on the Silesia compression corpus.

Compressor nameRatioCompressionDecompress.
zstd 1.5.6 -12.887510 MB/s1580 MB/s
zlib 1.2.11 -12.74395 MB/s400 MB/s
brotli 1.0.9 -02.702395 MB/s430 MB/s
zstd 1.5.6 --fast=12.437545 MB/s1890 MB/s
zstd 1.5.6 --fast=32.239650 MB/s2000 MB/s
quicklz 1.5.0 -12.238525 MB/s750 MB/s
lzo1x 2.10 -12.106650 MB/s825 MB/s
lz4 1.9.42.101700 MB/s4000 MB/s
lzf 3.6 -12.077420 MB/s830 MB/s
snappy 1.1.92.073530 MB/s1660 MB/s

The negative compression levels, specified with --fast=#, offer faster compression and decompression speed at the cost of compression ratio.

Zstd can also offer stronger compression ratios at the cost of compression speed. Speed vs Compression trade-off is configurable by small increments. Decompression speed is preserved and remains roughly the same at all settings, a property shared by most LZ compression algorithms, such as zlib or lzma.

The following tests were run on a server running Linux Debian (Linux version 4.14.0-3-amd64) with a Core i7-6700K CPU @ 4.0GHz, using lzbench, an open-source in-memory benchmark by @inikep compiled with gcc 7.3.0, on the Silesia compression corpus.

Compression Speed vs RatioDecompression Speed
Compression Speed vs RatioDecompression Speed

A few other algorithms can produce higher compression ratios at slower speeds, falling outside of the graph. For a larger picture including slow modes, click on this link.

The case for Small Data compression

Previous charts provide results applicable to typical file and stream scenarios (several MB). Small data comes with different perspectives.

The smaller the amount of data to compress, the more difficult it is to compress. This problem is common to all compression algorithms, and reason is, compression algorithms learn from past data how to compress future data. But at the beginning of a new data set, there is no "past" to build upon.

To solve this situation, Zstd offers a training mode, which can be used to tune the algorithm for a selected type of data. Training Zstandard is achieved by providing it with a few samples (one file per sample). The result of this training is stored in a file called "dictionary", which must be loaded before compression and decompression. Using this dictionary, the compression ratio achievable on small data improves dramatically.

The following example uses the github-users sample set, created from github public API. It consists of roughly 10K records weighing about 1KB each.

Compression RatioCompression SpeedDecompression Speed
Compression RatioCompression SpeedDecompression Speed

These compression gains are achieved while simultaneously providing faster compression and decompression speeds.

Training works if there is some correlation in a family of small data samples. The more data-specific a dictionary is, the more efficient it is (there is no universal dictionary). Hence, deploying one dictionary per type of data will provide the greatest benefits. Dictionary gains are mostly effective in the first few KB. Then, the compression algorithm will gradually use previously decoded content to better compress the rest of the file.

Dictionary compression How To:

  1. Create the dictionary

    zstd --train FullPathToTrainingSet/* -o dictionaryName

  2. Compress with dictionary

    zstd -D dictionaryName FILE

  3. Decompress with dictionary

    zstd -D dictionaryName --decompress FILE.zst

Build instructions

make is the officially maintained build system of this project. All other build systems are "compatible" and 3rd-party maintained, they may feature small differences in advanced options. When your system allows it, prefer using make to build zstd and libzstd.

Makefile

If your system is compatible with standard make (or gmake), invoking make in root directory will generate zstd cli in root directory. It will also create libzstd into lib/.

Other available options include:

  • make install : create and install zstd cli, library and man pages
  • make check : create and run zstd, test its behavior on local platform

The Makefile follows the GNU Standard Makefile conventions, allowing staged install, standard flags, directory variables and command variables.

For advanced use cases, specialized compilation flags which control binary generation are documented in lib/README.md for the libzstd library and in programs/README.md for the zstd CLI.

cmake

A cmake project generator is provided within build/cmake. It can generate Makefiles or other build scripts to create zstd binary, and libzstd dynamic and static libraries.

By default, CMAKE_BUILD_TYPE is set to Release.

Support for Fat (Universal2) Output

zstd can be built and installed with support for both Apple Silicon (M1/M2) as well as Intel by using CMake's Universal2 support. To perform a Fat/Universal2 build and install use the following commands:

cmake -B build-cmake-debug -S build/cmake -G Ninja -DCMAKE_OSX_ARCHITECTURES="x86_64;x86_64h;arm64"
cd build-cmake-debug
ninja
sudo ninja install

Meson

A Meson project is provided within build/meson. Follow build instructions in that directory.

You can also take a look at .travis.yml file for an example about how Meson is used to build this project.

Note that default build type is release.

VCPKG

You can build and install zstd vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install zstd

The zstd port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Conan

You can install pre-built binaries for zstd or build it from source using Conan. Use the following command:

conan install --requires="zstd/[*]" --build=missing

The zstd Conan recipe is kept up to date by Conan maintainers and community contributors. If the version is out of date, please create an issue or pull request on the ConanCenterIndex repository.

Visual Studio (Windows)

Going into build directory, you will find additional possibilities:

  • Projects for Visual Studio 2005, 2008 and 2010.
    • VS2010 project is compatible with VS2012, VS2013, VS2015 and VS2017.
  • Automated build scripts for Visual compiler by @KrzysFR, in build/VS_scripts, which will build zstd cli and libzstd library without any need to open Visual Studio solution.

Buck

You can build the zstd binary via buck by executing: buck build programs:zstd from the root of the repo. The output binary will be in buck-out/gen/programs/.

Bazel

You easily can integrate zstd into your Bazel project by using the module hosted on the Bazel Central Repository.

Testing

You can run quick local smoke tests by running make check. If you can't use make, execute the playTest.sh script from the src/tests directory. Two env variables $ZSTD_BIN and $DATAGEN_BIN are needed for the test script to locate the zstd and datagen binary. For information on CI testing, please refer to TESTING.md.

Status

Zstandard is currently deployed within Facebook and many other large cloud infrastructures. It is run continuously to compress large amounts of data in multiple formats and use cases. Zstandard is considered safe for production environments.

License

Zstandard is dual-licensed under BSD OR GPLv2.

Contributing

The dev branch is the one where all contributions are merged before reaching release. If you plan to propose a patch, please commit into the dev branch, or its own feature branch. Direct commit to release are not permitted. For more information, please read CONTRIBUTING.

NPM DownloadsLast 30 Days