Convert Figma logo to code with AI

Cyan4973 logoxxHash

Extremely fast non-cryptographic hash algorithm

8,937
770
8,937
32

Top Related Projects

15,631

A very compact representation of a placeholder for an image.

Automatically exported from code.google.com/p/cityhash

Automatically exported from code.google.com/p/smhasher

1,012

Superfast compression library

23,176

Zstandard - Fast real-time compression algorithm

Quick Overview

xxHash is an extremely fast non-cryptographic hash algorithm, working at speeds close to RAM limits. It is designed for speed on both 32-bit and 64-bit systems and has been thoroughly tested for reliability. The algorithm is available in both 32-bit and 64-bit versions, known as XXH32 and XXH64 respectively.

Pros

  • Exceptionally fast, often outperforming other non-cryptographic hash functions
  • Provides both 32-bit and 64-bit hash variants
  • Well-tested and reliable across various platforms
  • Offers a simple API for easy integration

Cons

  • Not suitable for cryptographic purposes due to its non-cryptographic nature
  • May require additional steps for big-endian architectures
  • Limited to 64-bit hash sizes at maximum (compared to some other algorithms that offer larger sizes)

Code Examples

  1. Basic usage of XXH64:
#include "xxhash.h"

const char* input = "Hello, World!";
XXH64_hash_t hash = XXH64(input, strlen(input), 0);
printf("Hash: %llx\n", hash);
  1. Streaming API for large inputs:
XXH64_state_t* state = XXH64_createState();
XXH64_reset(state, 0);
XXH64_update(state, chunk1, chunk1_len);
XXH64_update(state, chunk2, chunk2_len);
XXH64_hash_t hash = XXH64_digest(state);
XXH64_freeState(state);
  1. Using the oneshot function with a seed:
const void* input = some_data;
size_t length = data_length;
unsigned long long seed = 0xCBF29CE484222325ULL;
XXH64_hash_t hash = XXH64(input, length, seed);

Getting Started

To use xxHash in your project:

  1. Download the xxHash source from the GitHub repository.
  2. Include xxhash.h in your project.
  3. Compile xxhash.c along with your source files.

For a simple example:

#include "xxhash.h"
#include <stdio.h>
#include <string.h>

int main() {
    const char* input = "Test input";
    XXH64_hash_t hash = XXH64(input, strlen(input), 0);
    printf("Hash: %llx\n", hash);
    return 0;
}

Compile with: gcc -o example example.c xxhash.c

Competitor Comparisons

15,631

A very compact representation of a placeholder for an image.

Pros of BlurHash

  • Designed specifically for image placeholder generation, providing visually appealing blurred representations
  • Supports multiple programming languages and platforms
  • Generates compact, URL-safe strings for easy storage and transmission

Cons of BlurHash

  • Limited to image-related use cases, not suitable for general-purpose hashing
  • May have higher computational overhead for encoding/decoding compared to xxHash
  • Less widely adopted in the developer community

Code Comparison

BlurHash (Swift):

let blurHash = "LEHV6nWB2yk8pyo0adR*.7kCMdnj"
let image = UIImage(blurHash: blurHash, size: CGSize(width: 32, height: 32))

xxHash (C):

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

Key Differences

  • BlurHash focuses on visual representation, while xxHash is a fast non-cryptographic hash function
  • BlurHash output is human-readable and visually meaningful, xxHash produces numeric hash values
  • xxHash is more versatile for general hashing needs, while BlurHash is specialized for image placeholders
  • BlurHash has a larger codebase due to its specific functionality, xxHash is more compact and focused

Automatically exported from code.google.com/p/cityhash

Pros of CityHash

  • Optimized for x86-64 architecture, potentially offering better performance on compatible systems
  • Provides multiple hash functions with different output sizes (32, 64, 128, and 256 bits)
  • Well-established and widely used in Google's infrastructure

Cons of CityHash

  • Less portable across different architectures compared to xxHash
  • Not as actively maintained, with fewer recent updates
  • Generally slower than xxHash on most platforms

Code Comparison

CityHash:

uint64_t CityHash64(const char *buf, size_t len) {
  if (len <= 32) {
    if (len <= 16) {
      return HashLen0to16(buf, len);
    } else {
      return HashLen17to32(buf, len);
    }
  }
  // ... (additional code)
}

xxHash:

XXH64_hash_t XXH64(const void* input, size_t length, XXH64_hash_t seed) {
    if (input==NULL) return XXH64_EMPTY_SECRET;
    if (length >= 32) {
        return XXH64_internal_loop(input, length, seed);
    }
    return XXH64_small(input, length, seed);
}

Both hash functions use different approaches for small input sizes, with xxHash appearing more straightforward in its implementation.

Automatically exported from code.google.com/p/smhasher

Pros of SMHasher

  • Comprehensive test suite for hash functions
  • Supports multiple hash algorithms for comparison
  • Useful for evaluating and benchmarking hash function quality

Cons of SMHasher

  • Less focused on a single, optimized hash algorithm
  • Not as actively maintained as xxHash
  • May have lower performance for specific use cases

Code Comparison

SMHasher (test implementation):

void BulkSpeedTest(HashInfo* info)
{
  const int trials = 100;
  const int blocksize = 2048;
  uint8_t * block = new uint8_t[blocksize];
  memset(block,0,blocksize);

  //...
}

xxHash (core hashing function):

XXH_FORCE_INLINE XXH64_hash_t XXH64_round(XXH64_hash_t acc, XXH64_hash_t input)
{
    acc += input * XXH_PRIME64_2;
    acc  = XXH_rotl64(acc, 31);
    acc *= XXH_PRIME64_1;
    return acc;
}

Summary

SMHasher is a comprehensive test suite for hash functions, offering a wide range of tests and comparisons for multiple algorithms. It's valuable for evaluating hash function quality and performance. However, it's less focused on a single, optimized algorithm compared to xxHash, which prioritizes speed and efficiency for its specific hash function. xxHash is more actively maintained and may offer better performance for certain use cases. The code comparison shows SMHasher's focus on testing methodology, while xxHash emphasizes optimized hashing operations.

1,012

Superfast compression library

Pros of density

  • Focuses on compression rather than hashing, offering data reduction capabilities
  • Provides both compression and decompression functionality
  • Designed for high-speed operation, potentially faster for certain use cases

Cons of density

  • Less widely adopted and tested compared to xxHash
  • May have a larger memory footprint due to compression algorithms
  • Potentially more complex to integrate and use for simple hashing tasks

Code comparison

xxHash:

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

density:

density_processing_result result;
density_compress(&compress_state, input, input_size, output, output_size, &result);

Summary

While xxHash is primarily a fast non-cryptographic hashing algorithm, density focuses on high-speed compression and decompression. xxHash is more suitable for tasks like checksumming and hash tables, while density is better for reducing data size while maintaining speed. xxHash has a simpler API and is more widely adopted, but density offers additional functionality for applications requiring data compression. The choice between the two depends on the specific requirements of the project, with xxHash being more appropriate for simple hashing needs and density for compression-oriented tasks.

23,176

Zstandard - Fast real-time compression algorithm

Pros of zstd

  • Offers both compression and decompression, while xxHash is only a hashing algorithm
  • Generally provides better compression ratios than other popular algorithms like zlib
  • Includes a dictionary compression feature for improved efficiency with small files

Cons of zstd

  • Larger codebase and more complex implementation compared to xxHash's simplicity
  • Slightly slower performance for small data sizes due to its comprehensive nature
  • Requires more memory usage during compression/decompression processes

Code Comparison

xxHash (simple hash function):

XXH64_hash_t XXH64(const void* input, size_t length, XXH64_hash_t seed);

zstd (compression function):

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

Summary

While xxHash focuses on fast non-cryptographic hashing, zstd provides a full-featured compression library. xxHash is simpler and faster for small data, while zstd offers better compression ratios and more advanced features at the cost of increased complexity and resource usage.

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

xxHash - Extremely fast hash algorithm

xxHash is an Extremely fast Hash algorithm, processing at RAM speed limits. Code is highly portable, and produces hashes identical across all platforms (little / big endian). The library includes the following algorithms :

  • XXH32 : generates 32-bit hashes, using 32-bit arithmetic
  • XXH64 : generates 64-bit hashes, using 64-bit arithmetic
  • XXH3 (since v0.8.0): generates 64 or 128-bit hashes, using vectorized arithmetic. The 128-bit variant is called XXH128.

All variants successfully complete the SMHasher test suite which evaluates the quality of hash functions (collision, dispersion and randomness). Additional tests, which evaluate more thoroughly speed and collision properties of 64-bit hashes, are also provided.

BranchStatus
releaseBuild Status
devBuild Status

Benchmarks

The benchmarked reference system uses an Intel i7-9700K cpu, and runs Ubuntu x64 20.04. The open source benchmark program is compiled with clang v10.0 using -O3 flag.

Hash NameWidthBandwidth (GB/s)Small Data VelocityQualityComment
XXH3 (SSE2)6431.5 GB/s133.110
XXH128 (SSE2)12829.6 GB/s118.110
RAM sequential readN/A28.0 GB/sN/AN/Afor reference
City646422.0 GB/s76.610
T1ha26422.0 GB/s99.09Slightly worse collisions
City12812821.7 GB/s57.710
XXH646419.4 GB/s71.010
SpookyHash6419.3 GB/s53.210
Mum6418.0 GB/s67.09Slightly worse collisions
XXH32329.7 GB/s71.910
City32329.1 GB/s66.010
Murmur3323.9 GB/s56.110
SipHash643.0 GB/s43.210
FNV64641.2 GB/s62.75Poor avalanche properties
Blake22561.1 GB/s5.110Cryptographic
SHA11600.8 GB/s5.610Cryptographic but broken
MD51280.6 GB/s7.810Cryptographic but broken

note 1: Small data velocity is a rough evaluation of algorithm's efficiency on small data. For more detailed analysis, please refer to next paragraph.

note 2: some algorithms feature faster than RAM speed. In which case, they can only reach their full speed potential when input is already in CPU cache (L3 or better). Otherwise, they max out on RAM speed limit.

Small data

Performance on large data is only one part of the picture. Hashing is also very useful in constructions like hash tables and bloom filters. In these use cases, it's frequent to hash a lot of small data (starting at a few bytes). Algorithm's performance can be very different for such scenarios, since parts of the algorithm, such as initialization or finalization, become fixed cost. The impact of branch mis-prediction also becomes much more present.

XXH3 has been designed for excellent performance on both long and small inputs, which can be observed in the following graph:

XXH3, latency, random size

For a more detailed analysis, please visit the wiki : https://github.com/Cyan4973/xxHash/wiki/Performance-comparison#benchmarks-concentrating-on-small-data-

Quality

Speed is not the only property that matters. Produced hash values must respect excellent dispersion and randomness properties, so that any sub-section of it can be used to maximally spread out a table or index, as well as reduce the amount of collisions to the minimal theoretical level, following the birthday paradox.

xxHash has been tested with Austin Appleby's excellent SMHasher test suite, and passes all tests, ensuring reasonable quality levels. It also passes extended tests from newer forks of SMHasher, featuring additional scenarios and conditions.

Finally, xxHash provides its own massive collision tester, able to generate and compare billions of hashes to test the limits of 64-bit hash algorithms. On this front too, xxHash features good results, in line with the birthday paradox. A more detailed analysis is documented in the wiki.

Build modifiers

The following macros can be set at compilation time to modify libxxhash's behavior. They are generally disabled by default.

  • XXH_INLINE_ALL: Make all functions inline, implementation is directly included within xxhash.h. Inlining functions is beneficial for speed, notably for small keys. It's extremely effective when key's length is expressed as a compile time constant, with performance improvements observed in the +200% range . See this article for details.
  • XXH_PRIVATE_API: same outcome as XXH_INLINE_ALL. Still available for legacy support. The name underlines that XXH_* symbol names will not be exported.
  • XXH_STATIC_LINKING_ONLY: gives access to internal state declaration, required for static allocation. Incompatible with dynamic linking, due to risks of ABI changes.
  • XXH_NAMESPACE: Prefixes all symbols with the value of XXH_NAMESPACE. This macro can only use compilable character set. Useful to evade symbol naming collisions, in case of multiple inclusions of xxHash's source code. Client applications still use the regular function names, as symbols are automatically translated through xxhash.h.
  • XXH_FORCE_ALIGN_CHECK: Use a faster direct read path when input is aligned. This option can result in dramatic performance improvement on architectures unable to load memory from unaligned addresses when input to hash happens to be aligned on 32 or 64-bit boundaries. It is (slightly) detrimental on platform with good unaligned memory access performance (same instruction for both aligned and unaligned accesses). This option is automatically disabled on x86, x64 and aarch64, and enabled on all other platforms.
  • XXH_FORCE_MEMORY_ACCESS: The default method 0 uses a portable memcpy() notation. Method 1 uses a gcc-specific packed attribute, which can provide better performance for some targets. Method 2 forces unaligned reads, which is not standard compliant, but might sometimes be the only way to extract better read performance. Method 3 uses a byteshift operation, which is best for old compilers which don't inline memcpy() or big-endian systems without a byteswap instruction.
  • XXH_CPU_LITTLE_ENDIAN: By default, endianness is determined by a runtime test resolved at compile time. If, for some reason, the compiler cannot simplify the runtime test, it can cost performance. It's possible to skip auto-detection and simply state that the architecture is little-endian by setting this macro to 1. Setting it to 0 states big-endian.
  • XXH_ENABLE_AUTOVECTORIZE: Auto-vectorization may be triggered for XXH32 and XXH64, depending on cpu vector capabilities and compiler version. Note: auto-vectorization tends to be triggered more easily with recent versions of clang. For XXH32, SSE4.1 or equivalent (NEON) is enough, while XXH64 requires AVX512. Unfortunately, auto-vectorization is generally detrimental to XXH performance. For this reason, the xxhash source code tries to prevent auto-vectorization by default. That being said, systems evolve, and this conclusion is not forthcoming. For example, it has been reported that recent Zen4 cpus are more likely to improve performance with vectorization. Therefore, should you prefer or want to test vectorized code, you can enable this flag: it will remove the no-vectorization protection code, thus making it more likely for XXH32 and XXH64 to be auto-vectorized.
  • XXH32_ENDJMP: Switch multi-branch finalization stage of XXH32 by a single jump. This is generally undesirable for performance, especially when hashing inputs of random sizes. But depending on exact architecture and compiler, a jump might provide slightly better performance on small inputs. Disabled by default.
  • XXH_IMPORT: MSVC specific: should only be defined for dynamic linking, as it prevents linkage errors.
  • XXH_NO_STDLIB: Disable invocation of <stdlib.h> functions, notably malloc() and free(). libxxhash's XXH*_createState() will always fail and return NULL. But one-shot hashing (like XXH32()) or streaming using statically allocated states still work as expected. This build flag is useful for embedded environments without dynamic allocation.
  • XXH_DEBUGLEVEL : When set to any value >= 1, enables assert() statements. This (slightly) slows down execution, but may help finding bugs during debugging sessions.

Binary size control

  • XXH_NO_XXH3 : removes symbols related to XXH3 (both 64 & 128 bits) from generated binary. XXH3 is by far the largest contributor to libxxhash size, so it's useful to reduce binary size for applications which do not employ XXH3.
  • XXH_NO_LONG_LONG: removes compilation of algorithms relying on 64-bit long long types which include XXH3 and XXH64. Only XXH32 will be compiled. Useful for targets (architectures and compilers) without 64-bit support.
  • XXH_NO_STREAM: Disables the streaming API, limiting the library to single shot variants only.
  • XXH_NO_INLINE_HINTS: By default, xxHash uses __attribute__((always_inline)) and __forceinline to improve performance at the cost of code size. Defining this macro to 1 will mark all internal functions as static, allowing the compiler to decide whether to inline a function or not. This is very useful when optimizing for smallest binary size, and is automatically defined when compiling with -O0, -Os, -Oz, or -fno-inline on GCC and Clang. This might also increase performance depending on compiler and architecture.
  • XXH_SIZE_OPT: 0: default, optimize for speed 1: default for -Os and -Oz: disables some speed hacks for size optimization 2: makes code as small as possible, performance may cry

Build modifiers specific for XXH3

  • XXH_VECTOR : manually select a vector instruction set (default: auto-selected at compilation time). Available instruction sets are XXH_SCALAR, XXH_SSE2, XXH_AVX2, XXH_AVX512, XXH_NEON and XXH_VSX. Compiler may require additional flags to ensure proper support (for example, gcc on x86_64 requires -mavx2 for AVX2, or -mavx512f for AVX512).
  • XXH_PREFETCH_DIST : select prefetching distance. For close-to-metal adaptation to specific hardware platforms. XXH3 only.
  • XXH_NO_PREFETCH : disable prefetching. Some platforms or situations may perform better without prefetching. XXH3 only.

Makefile variables

When compiling the Command Line Interface xxhsum using make, the following environment variables can also be set :

  • DISPATCH=1 : use xxh_x86dispatch.c, to automatically select between scalar, sse2, avx2 or avx512 instruction set at runtime, depending on local host. This option is only valid for x86/x64 systems.
  • XXH_1ST_SPEED_TARGET : select an initial speed target, expressed in MB/s, for the first speed test in benchmark mode. Benchmark will adjust the target at subsequent iterations, but the first test is made "blindly" by targeting this speed. Currently conservatively set to 10 MB/s, to support very slow (emulated) platforms.
  • NODE_JS=1 : When compiling xxhsum for Node.js with Emscripten, this links the NODERAWFS library for unrestricted filesystem access and patches isatty to make the command line utility correctly detect the terminal. This does make the binary specific to Node.js.

Building xxHash - Using vcpkg

You can download and install xxHash using the vcpkg dependency manager:

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

The xxHash 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.

Example

The simplest example calls xxhash 64-bit variant as a one-shot function generating a hash value from a single buffer, and invoked from a C/C++ program:

#include "xxhash.h"

    (...)
    XXH64_hash_t hash = XXH64(buffer, size, seed);
}

Streaming variant is more involved, but makes it possible to provide data incrementally:

#include "stdlib.h"   /* abort() */
#include "xxhash.h"


XXH64_hash_t calcul_hash_streaming(FileHandler fh)
{
    /* create a hash state */
    XXH64_state_t* const state = XXH64_createState();
    if (state==NULL) abort();

    size_t const bufferSize = SOME_SIZE;
    void* const buffer = malloc(bufferSize);
    if (buffer==NULL) abort();

    /* Initialize state with selected seed */
    XXH64_hash_t const seed = 0;   /* or any other value */
    if (XXH64_reset(state, seed) == XXH_ERROR) abort();

    /* Feed the state with input data, any size, any number of times */
    (...)
    while ( /* some data left */ ) {
        size_t const length = get_more_data(buffer, bufferSize, fh);
        if (XXH64_update(state, buffer, length) == XXH_ERROR) abort();
        (...)
    }
    (...)

    /* Produce the final hash value */
    XXH64_hash_t const hash = XXH64_digest(state);

    /* State could be re-used; but in this example, it is simply freed  */
    free(buffer);
    XXH64_freeState(state);

    return hash;
}

License

The library files xxhash.c and xxhash.h are BSD licensed. The utility xxhsum is GPL licensed.

Other programming languages

Beyond the C reference version, xxHash is also available from many different programming languages, thanks to great contributors. They are listed here.

Packaging status

Many distributions bundle a package manager which allows easy xxhash installation as both a libxxhash library and xxhsum command line interface.

Packaging status

Special Thanks

  • Takayuki Matsuoka, aka @t-mat, for creating xxhsum -c and great support during early xxh releases
  • Mathias Westerdahl, aka @JCash, for introducing the first version of XXH64
  • Devin Hussey, aka @easyaspi314, for incredible low-level optimizations on XXH3 and XXH128