Fastest way to determine if two values in array add up to zero

JavaScript performance comparison

Test case created by Calvin Tennant

Preparation code

<script src="//underscorejs.org/underscore-min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var arr = [], hash = {}, validArr = false, variance = 1000000, 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:

0 comments

Add a comment