finding numbers - array search vs associative object

JavaScript performance comparison

Test case created by finding numbers - array search vs associative object

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    Array.prototype.shuffle = function () {
        var m = this.length, t, i;
       
        // While there remain elements to shuffle…
                while (m) {
            // Pick a remaining element…
            i = Math.floor(Math.random() * m--);
   
            // And swap it with the current element.
            t = this[m];
            this[m] = this[i];
            this[i] = t;
                }
    };
   
    //given a target x and an array, find any pairs of elements whose sum is x
    var x = 555;
    var arr = [];
    for (var i=0; i<1000;i++) { arr.push(i) } ;  
    arr.shuffle();
    var arr2 = arr.slice(0,arr.length);
    var arrObj = {};
};
</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
array search with indexOf
var count = 0; 
for (var i=0; i<arr.length; i++) {
   var target = x-arr[i];
   if (target < 0) { continue; }
   if (arr2.indexOf(target) != -1) {
      count++;
            continue;
        }
}
pending…
associative object/array
var count=0; 
for (var i=0; i<arr.length; i++) {
        arrObj[arr[i]]=arr[i];
}
for (var i=0; i<arr.length; i++) {
        var target = x-arr[i];
  if (target < 0) { continue; }  //if arr is sorted, could break instead
        if (arrObj[target]) {
      count++;
            continue;
        }
}
pending…

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

Compare results of other browsers

0 comments

Add a comment