Skip to content

Instantly share code, notes, and snippets.

@RedGateway
Created March 11, 2021 14:54
Show Gist options
  • Save RedGateway/3dfab8a93df66cff8bcebea1cac60919 to your computer and use it in GitHub Desktop.
Save RedGateway/3dfab8a93df66cff8bcebea1cac60919 to your computer and use it in GitHub Desktop.
Test for hash collisions
const { crc32 } = require('@node-rs/crc32');
const randomString = require('random-string');
const murmur = require('murmur2js');
//const siphash = require('siphash');
//const sipkey = siphash.string16_to_key(randomString({length: 16}));
const values = 16000000;
let collisions = 0;
const map = new Map();
const t1 = new Date().getTime();
for (let i = 1; i <= values; i++) {
const str = randomString({length: 16});
const crc32Hash = crc32(str);
//const murmurHash = murmur(str);
//const hash = ((crc32Hash & 0xfffff) * 2 ** 32) + murmurHash;
//const hash = siphash.hash_uint(sipkey, str);
const hash = crc32Hash;
if (map.has(hash)) {
collisions++;
//console.log(`Collision: hash(${str}) = hash(${map.get(hash)})!`);
}
map.set(hash, str);
if (!(i % 100000)) {
if (collisions)
console.log(`Added ${i} values, one collision for ${ Math.round(i / collisions) } elements`);
else
console.log(`Added ${i} values, still no collisions!`);
}
}
const t2 = new Date().getTime();
console.log(`Total values: ${values}, collisions: ${collisions} in ${(t2-t1)/1000} seconds`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment