jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
Three common string-to-integer hash functions compared.
Reference: http://erlycoder.com/49/javascript-hash-functions-to-convert-string-into-integer-hash
<dl>
<dt>hashCode() hash:</dt>
<dd id="hashcode"></dd>
<dt>djb2code() hash:</dt>
<dd id="djb2code"></dd>
<dt>sdbmcode() hash:</dt>
<dd id="sdbmcode"></dd>
<dt>str2hash() hash:</dt>
<dd id="str2hash"></dd>
</dl>var str = 'Lorem ipsum',
nHashCode,
nDjb2Code,
nSdbmCode,
nStr2hash;
function hashCode(str) {
var hash = 0;
if (str.length == 0) return hash;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
function djb2Code(str) {
var hash = 5381;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
}
return hash;
}
function sdbmCode(str) {
var hash = 0;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = char + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
// Tom's modified version of hashCode()
// Also ensure hash is non-negative
function str2hash(s) {
var nHash = 0;
if (!s.length) return nHash;
for (var i=0,imax=s.length,n; i<imax; ++i) {
n = s.charCodeAt(i);
nHash = ((nHash<<5)-nHash)+n;
nHash = nHash & nHash; // Convert to 32-bit integer
}
return Math.abs(nHash);
}
if (nHashCode) document.getElementById('hashcode').innerHTML = nHashCode;
if (nDjb2Code) document.getElementById('djb2code').innerHTML = nDjb2Code;
if (nSdbmCode) document.getElementById('sdbmcode').innerHTML = nSdbmCode;
if (nStr2hash) document.getElementById('str2hash').innerHTML = nStr2hash;
Ready to run.
| Test | Ops/sec | |
|---|---|---|
| hashCode | | ready |
| djb2 | | ready |
| sdbm | | ready |
| str2hash | | ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.