Created
April 15, 2025 05:15
-
-
Save souporserious/cbedfad6c378bf8920dc5520169f96c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function compareHashPerformance(input = 'body { margin: 0; padding: 0; }', iterations = 100000) { | |
// FNV-1a Hash Function (with Base36 Encoding) | |
function fnvHash(str) { | |
let h = 0 ^ 0x811c9dc5; | |
for (let i = 0; i < str.length; i++) { | |
h ^= str.charCodeAt(i); | |
h = (h * 0x01000193) >>> 0; | |
} | |
const letters = 'abcdefghijklmnopqrstuvwxyz'; | |
const base36 = '0123456789' + letters; | |
let result = ''; | |
do { | |
result = base36[h % 36] + result; | |
h = Math.floor(h / 36); | |
} while (h > 0); | |
return result; | |
} | |
// djb2 Hash Function | |
function djb2Hash(str) { | |
let hash = 5381; | |
for (let i = 0; i < str.length; i++) { | |
hash = ((hash << 5) + hash + str.charCodeAt(i)) >>> 0; | |
} | |
return '_' + hash.toString(36); | |
} | |
// Benchmark FNV-1a hash | |
const startFnv = performance.now(); | |
for (let i = 0; i < iterations; i++) { | |
fnvHash(input); | |
} | |
const timeFnv = performance.now() - startFnv; | |
// Benchmark djb2 hash | |
const startDjb2 = performance.now(); | |
for (let i = 0; i < iterations; i++) { | |
djb2Hash(input); | |
} | |
const timeDjb2 = performance.now() - startDjb2; | |
console.log(`FNV-1a Hash: ${timeFnv.toFixed(2)} ms for ${iterations} iterations.`); | |
console.log(`djb2 Hash: ${timeDjb2.toFixed(2)} ms for ${iterations} iterations.`); | |
// Determine which is faster and calculate factor and percentage difference. | |
if (timeFnv < timeDjb2) { | |
const factor = timeDjb2 / timeFnv; | |
const percentageFaster = (1 - timeFnv / timeDjb2) * 100; | |
console.log(`FNV-1a hash is faster by a factor of ${factor.toFixed(2)} (approximately ${percentageFaster.toFixed(2)}% faster).`); | |
} else if (timeFnv > timeDjb2) { | |
const factor = timeFnv / timeDjb2; | |
const percentageFaster = (1 - timeDjb2 / timeFnv) * 100; | |
console.log(`djb2 hash is faster by a factor of ${factor.toFixed(2)} (approximately ${percentageFaster.toFixed(2)}% faster).`); | |
} else { | |
console.log('Both hash functions performed similarly.'); | |
} | |
} | |
// Run the comparison with default CSS rule input and 100,000 iterations. | |
compareHashPerformance('body { margin: 0; padding: 0; }', 10_000_000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment