Skip to content

Instantly share code, notes, and snippets.

@feeedback
Last active September 27, 2024 08:53
Show Gist options
  • Save feeedback/e6d137d3f54b1aa0310d690daadfaf28 to your computer and use it in GitHub Desktop.
Save feeedback/e6d137d3f54b1aa0310d690daadfaf28 to your computer and use it in GitHub Desktop.
fastest and simple string hash function (10^9 hashes => zero collision)
/*
source: stackoverflow.com/a/52171480
author: stackoverflow.com/users/815680/bryc
license: i think CC BY-SA 4.0 stackoverflow.com/help/licensing
*/
// fastest and simple string hash function (10^9 hashes => zero collision)
// keys 20 length => 1050 hash/ms
// keys 50 length => 750 hash/ms
// keys 500 length => 80 hash/ms
const cyrb53 = (key, seed = 0) => {
const A = 2654435761;
const B = 1597334677;
const C = 2246822507;
const D = 3266489909;
const E = 4294967296;
const F = 2097151;
let h1 = 0xdeadbeef ^ seed;
let h2 = 0x41c6ce57 ^ seed;
for (let index = 0, char; index < key.length; index++) {
char = key.charCodeAt(index);
h1 = Math.imul(h1 ^ char, A);
h2 = Math.imul(h2 ^ char, B);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), C) ^ Math.imul(h2 ^ (h2 >>> 13), D);
h2 = Math.imul(h2 ^ (h2 >>> 16), C) ^ Math.imul(h1 ^ (h1 >>> 13), D);
return E * (F & h2) + (h1 >>> 0);
};
@suchipi
Copy link

suchipi commented May 9, 2022

what is the license on this code?

@feeedback
Copy link
Author

feeedback commented May 10, 2022

@bryc
Copy link

bryc commented May 14, 2022

I posted it on GH as public domain: https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js, this supersedes the SA license. Do whatever with it. Other hashes and PRNGs here: https://github.com/bryc/code/tree/master/jshash

@suchipi
Copy link

suchipi commented May 16, 2022

thank you, @bryc!!! fuck software license bs, public domain ftw

@igrek8
Copy link

igrek8 commented Sep 14, 2024

Thank you for posting this hashing algorithm.

In my case the algorithm produced collision for 0392f76e0adca5c990b8918d904fdeeb and ee136ef394ea64ba60f727b11d19a731in 436_207_616 iteration so the statement "10^9 hashes => zero collision" may not be accurate though.

console.log(cyrb53("0392f76e0adca5c990b8918d904fdeeb")); // 4399253915980964
console.log(cyrb53("ee136ef394ea64ba60f727b11d19a731")); // 4399253915980964

@ddd89-stack
Copy link

Hi, I would like to find the key based on the output generated from this code.
Can you pls help?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment