hashVsIterate

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var totalItems = 18000;
    var duplicatePercent = 10; // try and add 10 % duplicates
    var uniqueTotal = Math.floor(((100 - duplicatePercent)/100) * totalItems);
   
    // Don't screw with me
    if(duplicatePercent === 0) {
      uniqueTotal = totalItems;
    }
   
    var arrayStruct = [];
    var hashStruct = {};
   
    var functionLength = 200;
   
    //some long string (simulates how much work the hasher will need to do
    var boringString = new Array(functionLength + 1).join( 'a' );
   
    //build up new funcs
    var funcs = [];
    for(var i = 0;i<totalItems;i++){
     
      funcs[i] = eval("(function(){ return '" + boringString + (i%uniqueTotal) + "';})");
    }
   
    String.prototype.hashCode = function(){
        var hash = 0, i, char;
        if (this.length === 0) return hash;
        for (i = 0, l = this.length; i < l; i++) {
            char  = this.charCodeAt(i);
            hash  = ((hash<<5)-hash)+char;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    };
   
    // this won't work in old browsers
    String.prototype.fastHash = function(){
      return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);              
    }
   
    arrayInject = function(item){
      for(var i = 0, l = arrayStruct.length;i<l;i++){
        if(arrayStruct[i] === item){
          return;
        }
      }
      arrayStruct[arrayStruct.length] = item;
    };
   
   
    hashInject = function(item){
      var hash = String(item).hashCode(),
          curArr;
   
    // pretend like we don't need to create an array, in case the target is different, this is just testing method
      if(!hashStruct[hash]){
        hashStruct[hash] = item;
      }
    };
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
for loop
for( var i = 0;i<totalItems;i++){
  arrayInject(funcs[i]);
}
pending…
hash inject
for( var i = 0;i<totalItems;i++){
  hashInject(funcs[i]);
}
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:

0 comments

Add a comment