Hashing strings

JavaScript performance comparison

Revision 6 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() {
    function bitwise(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;
      }
      return hash;
    }
   
    function numbers(str) {
      var res = 0,
          len = str.length;
      for (var i = 0; i < len; i++) {
        res = res * 31 + str.charCodeAt(i);
      }
      res = res & res;
      return res;
    }
   
    function bitwiseconv(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 numbersconv(str) {
      var res = 0,
          len = str.length;
      for (var i = 0; i < len; i++) {
        res = res * 31 + str.charCodeAt(i);
        res = res & res;
      }
      return res;
    }
   
    function hashcode(str) {
      var hash = 0;
      if (str.length == 0) return hash;
      for (var i = 0; i < str.length; i++) {
        var char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
      }
      hash = hash & hash; // Convert to 32bit integer
      return hash;
    }
};
</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…
Java hashCode
hashcode('[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:

1 comment

Frédéric Hewitt commented :

This test says very little about what it's supposed to compare. The absence of the "if" condition and the calculation of the string length prior to the loop in two functions, prevent any conclusion on the calculation method.

Add a comment