Hash in JS

Gen­er­at­ing hash­es from strings is a very handy thing to have. Sur­pris­ing­ly, in JavaScript, an arith­metic-oper­a­tion-based algo­rithm is about *three times* faster than one using bit-wise oper­a­tors–see for your­self. I sug­gest­ed to add the most per­for­mant method as hash method to underscore.string.js.

So much about state­ments on stack­over­flow like

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

(cf. here)

In times of inter­pret­ed lan­guages and vir­tu­al machi­nes one should recon­sid­er before apply­ing the same old rules again.

p.s. If you know about alter­na­tive algorithms/implementations, please add them to the test and leave a com­ment here, I’m curi­ous to see what else there is. Btw. I was very sur­prised that the neat reduce-based ver­sion failed so mis­er­ably.

Leave a Reply

Your email address will not be published. Required fields are marked *