determine if 2 values in array add up to 0 (small array)

JavaScript performance comparison

Revision 2 of this test case created by tomByrer

Info

Forked from a test with a huge 1000000 member array. It would stall out my Note2 smartphone. & allow less than 10 iterations on my i7 CPU.

Also switched from underscore.js to lo-dash.

Preparation code

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/1.1.1/lodash.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var arr = [], hash = {}, validArr = false, variance = 99, i, j;
    for (i = 0; i < variance; i++) {
      arr.push(_.random(-variance, variance))
    }
};

Benchmark.prototype.teardown = function() {
    delete arr, i, j, hash, validArr;
};
</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
Two dimensional check
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < arr.length; j++) {
    if (arr[i] + arr[j] === 0) {
      validArr = true;
      return validArr;
    }
  }
}
return validArr;
pending…
Hash-value check
for (i = 0; i < arr.length; i++) {
  hash[arr[i]] = true;
  if (hash[-arr[i]] === true) {
      validArr = true;
      break;
  }
}
return validArr;
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:

1 comment

tomByrer (revision owner) commented :

Shrinking the array from 1million to 100 gave very drastic change in results. The old 1m array worked best in the hash-value test hands down. This smaller array test, FireFox is indifferent, & Chrome23 shows that it prefers the 2d array test.

This proves that when dealing with arrays, not to rely on someone's array size if your array is much different.

Add a comment