Hashing strings
JavaScript performance comparison
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);
}
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;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Bitwise based function (No integer conversion) |
|
pending… |
Number based function (No integer conversion) |
|
pending… |
Bitwise based function |
|
pending… |
Number based function |
|
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:
- Revision 1: published by Jelle De Loecker
- Revision 2: published
- Revision 5: published
- Revision 6: published
- Revision 8: published
- Revision 10: published
- Revision 11: published
- Revision 12: published by Erwinus
- Revision 13: published by Yehor
- Revision 14: published
- Revision 17: published
- Revision 18: published
1 comment
Hai, nice test. Because i cannot change the code on this page, i would recommend to use while loops instead of for loops.