-
Notifications
You must be signed in to change notification settings - Fork 25
Closed
Description
With minimal additional code, the string-based hash functions, like cyrb53, could work with any numeric array-like input, like Uint8Array, Uint16Array, Buffer etc. Below you can find a sample script where I did this for cyrb53a. Running the script as node cyrb53a.js 0 will run a ~20sec benchmark for the original version, running node cyrb53a.js 1 will do the same for the modified version. On my system (Ubuntu 16.04, AMD Ryzen 7 1700) with Node.js v12.19 and v14.15 both versions perform about the same, i.e. the additional code does not seem to hinder V8's Turbofan from optimizing the function like the original one.
PS: Keep up the good work. This repository is a real treasure trove for hash enthusiasts :)
// ORIGINAL VERSION
const cyrb53a = function(str, seed = 0) {
let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
for(let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 0x85ebca77);
h2 = Math.imul(h2 ^ ch, 0xc2b2ae3d);
}
h1 ^= Math.imul(h1 ^ (h2 >>> 15), 0x735a2d97);
h2 ^= Math.imul(h2 ^ (h1 >>> 15), 0xcaf649a9);
h1 ^= h2 >>> 16; h2 ^= h1 >>> 16;
return 2097152 * (h2 >>> 0) + (h1 >>> 11);
};
// MODIFIED VERSION
const cyrb53a_1=function(x,seed=0){
var i,c,l=x.length,imul=Math.imul,h1=0xdeadbeef^seed,h2=0x41c6ce57^seed;
if (typeof(x)==="string") {
for (i=0;i<l;i++) {
c=x.charCodeAt(i);
h1=imul(h1^c,0x85ebca77);
h2=imul(h2^c,0xc2b2ae3d);
}
} else {
for (i=0;i<l;i++) {
c=x[i];
h1=imul(h1^c,0x85ebca77);
h2=imul(h2^c,0xc2b2ae3d);
}
}
h1^=imul(h1^(h2>>>15),0x735a2d97);
h2^=imul(h2^(h1>>>15),0xcaf649a9);
h1^=h2>>>16;h2^=h1>>>16;
return 2097152*(h2>>>0)+(h1>>>11);
}
// BENCHMARKING
var i,j,l,s,a,
fromCc=String.fromCharCode,
rnd=Math.random,trunc=Math.trunc,
cl=console.log,ct=console.time,cte=console.timeEnd,
f=(process.argv[2]==="1"?cyrb53a_1:cyrb53a);
// generate random string (100K)
a=new Array(l=1e5);
for (i=0;i<l;i++) a[i]=trunc(rnd()*65536);
s=fromCc.apply(String,a);
// start benchmark after 5s process relaxation
cl("benchmarking",f.name,"...");
setTimeout(()=>{
// start warmup run (10K*100K=1G)
l=1e4;
for (i=0;i<l;i++) f(s);
// start actual benchmark run (100K*100K=10G)
l=1e5;
ct(":");
for (i=0;i<l;i++) f(s);
cte(":");
},5000);Metadata
Metadata
Assignees
Labels
No labels