I was looking at methods of hashing a string, when I noticed something very weird with my methods of optimization. I was trying to (unsafely) hash a bunch of strings and compare performance, and I took an excerpt out of this answer. My rig was as follows:
String.prototype.hash = function() {
let hash = 0;
for (let i = 0, len = this.length; i < len; i++) {
let char = this.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash;
}
let startDate = new Date().getTime();
for (let i = 0; i < 11111111; i++) 'Hello World!'.hash();
// Log the time before and after the loop.
console.log(new Date().getTime() - startDate);
// (int) => 9358
When hashing 11111111 strings of “Hello World”, I get a modest result of 9000 ms for the full execution. I figured eh, makes sense, it's a lot to compute. However, when I defined a regular function (see code below) to compute the hashes, I get an execution time of 250 milliseconds! 1/36 of what would've been with the prototype function.
function hashStr(string) {
let hash = 0;
for (let i = 0, len = string.length; i < len; i++) {
let char = string.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash;
}
let startDate = new Date().getTime();
for (let i = 0; i < 11111111; i++) hashStr('Hello World!');
// Log the time before and after the loop.
console.log(new Date().getTime() - startDate);
// (int) => 280
Is there something that I'm missing, is it a fault with my code? I can't imagine it's THAT much faster to compute without using prototype. Thanks for the help!