Hashing strings

JavaScript performance comparison

Revision 14 of this test case created

Info

Looking for the fastest hash function to get a unique id of a string.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    // Erwin Haantjes, optimize code and use while loops
   
    function bitwise(str){
        var hash = 0,i=(str && str.length)?str.length:0;
        while(i--) { hash = ((hash<<5)-hash)+str.charCodeAt(i); }
        return hash;
    }
   
    function numbers(str) {
       var res = 0,i=(str && str.length)?str.length:0;
       while(i--) { res = res * 31 + str.charCodeAt(i); }
       return res;
      }
   
    function dodgyNumbers(str) {
       var res = 0,i=(str && str.length)?str.length:0;
       while(i -= 4 > 0) { res = res * 31 + str.charCodeAt(i); }
       return res;
      }
   
   
    function bitwiseconv(str){
        var hash = 0,i=(str && str.length)?str.length:0;
        while(i--)
        {
            hash = ((hash<<5)-hash)+str.charCodeAt(i);
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    }
   
    function numbersconv(str) {
      for(var res = 0, len = str && str.length || 0, j = 0; j < len; j++){
        res = (res * 31 + str.charCodeAt(j)) | 0;
      }
      return res;
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Bitwise based function (No integer conversion)
bitwise('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application');
pending…
Number based function (No integer conversion)
numbers('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application');
pending…
Bitwise based function
bitwiseconv('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application');
pending…
Number based function
numbersconv('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application');
pending…
Dodgy numbers
dodgyNumbers('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application');
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment