DJBHash (v6)

Revision 6 of this benchmark created on


Description

Test the performance of the simplest hash function ever

Setup

// Build a lot of average length string to test on
    
    var strs=[];
    
    var strbuff = 'a';
    for (var i = 0; i < 1000; i++) {
      var lc = strbuff.charAt(strbuff.length - 1);
      if (lc == 9) {
        strbuff += 'a';
      } else if (lc == 'z') {
        strbuff = strbuff.substr(0,strbuff.length -1);
        strbuff += 'A';
      } else if (lc == 'Z') {
        strbuff = strbuff.substr(0,strbuff.length -1);
        strbuff += '0';
      } else {
        strbuff = strbuff.substr(0,strbuff.length -1);
        strbuff += String.fromCharCode(lc.charCodeAt(0)+1);
      }
      strs.push(strbuff);        
    }
    
    function DJBHash(str) {
        var hash = 5381;
        
        for(var i = 0; i < str.length; i++) {
            hash = ((hash << 5) + hash) + str.charCodeAt(i);
        }
        
        return hash >>> 0;
    }
    
    function DJBHash2(str) {
        var hash = 5381;
        
        for(var i = 0; i < str.length; i++) {
            hash = 33 * hash + str.charCodeAt(i) >>> 0;
        }
        
        return hash;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
DJB on randoms
DJBHash(strs[Math.floor(Math.random() * 1000)]);
ready
DJB on average
DJBHash('abcdefghijklmnopqrstuvwxyz');
ready
DJB2 on randoms
DJBHash2(strs[Math.floor(Math.random() * 1000)]);
ready
DJB2 on average
DJBHash2('abcdefghijklmnopqrstuvwxyz');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.