Hash in JS

Posted 12/9/2013

Hash in JS

Generating hashes from strings can be very handy. Surprisingly, in JavaScript, an arithmetic-operation-based algorithm is about three times faster than one using bit-wise operators—see for yourself (archive). I suggested to add the most performant method as hash method to underscore.string.js.

The code is simple:

  hash: function (str) {
    var hash = 0, len = str.length
    if (len == 0) return hash;
    for (var i = 0; i < len; i++) { 
      hash = hash * 31 + str.charCodeAt(i); 
    return hash;

It might be time to end statements on Stack Overflow along the lines of…

hash << 5 - hash is the same as hash * 31 + char but a LOT faster.

In times of interpreted languages and virtual machines one should reconsider if applying the same old rules still makes sense.

p.s. I was very surprised that the neat reduce-based version failed so miserably.