Hashing strings (v25)

Revision 25 of this benchmark created by ICKX on


Description

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

Setup

function bitwise(str){
        var hash = 0, len = str.length
        if (len == 0) return hash;
        for (var i = 0; i < len; i++) {
            char = str.charCodeAt(i);
            hash = ((hash<<5)-hash)+char;
        }
        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 bitwiseconv(str){
        var hash = 0, len = str.length
        if (len == 0) return hash;
        for (var i = 0; i < len; i++) {
            hash = ((hash<<5)-hash)+str.charCodeAt(i);
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    }
    
    function numbersconv(str) {
        var hash = 0,i=(str && str.length)?str.length:0;
        while(i--) { hash = (hash * 31 + str.charCodeAt(i)) | 0; }
        return hash;
    }
    
    function bitwiseReduce(str){
        return str.split("").reduce(function(a,b)
            {a=((a<<5)-a)+b.charCodeAt(0);return a&a}
        ,0);              
    }
    
    HasH = function (str) { 
                var hash = 0;
                for (var i = 0, l = str.length; i < l; i++) {
                        hash = hash << 7 ^ str.charCodeAt(i);
                }
                return hash;
    }

Test runner

Ready to run.

Testing in
TestOps/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');
ready
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');
ready
Bitwise based function
bitwiseconv('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application');
ready
Number based function
numbersconv('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application');
ready
Reduce + bitwise
bitwiseReduce('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application')
ready
HasH
HasH('[LOG] This is a a not-too-long log message, once that will commonly pop up in my application');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.