Hash in JS

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

So much about statements on stackoverflow like

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

(cf. here)

In times of interpreted languages and virtual machines one should reconsider before applying the same old rules again.

p.s. If you know about alternative algorithms/implementations, please add them to the test and leave a comment here, I'm curious to see what else there is. Btw. I was very surprised that the neat reduce-based version failed so miserably.

Leave a Reply

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