skbtest2 (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script>
  a = [];
  for (var i = -1000000; i < 1000000; i++) {
   if (Math.random() > 0.5) {
    a.push(i);
   }
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
t1
function solve(a) {
 return a.filter(function(v, i, a) {
  return a.indexOf(-v) !== -1 && v > 0;
 });
}

solve(a);
ready
t2
solve = function(a) {
 for (var i = 0, t = [], r = [], n = a.length, v; i < n; i++) {
  if (t[(v = Math.abs(a[i]))]) {
   r[r.length] = v;
  }
  t[v] = v;
 }
 return r;
}
solve(a);
ready
winner
solve = function(input) {
 var output = [];
 var length = input.length;
 var a, b; // "cache"
 // iteruje tablicę input od początku i od końca, porównując kolejno
 // wartość bezwzględną elementów
 for (
 var i = 0, j = ~ - length, a = -input[0];
 (a = -input[i]) > 0; ++i) {
  // mały boost - po pierwsze zatrzymaj się tu, bo i tak nie spotkasz
  // wartości równych, po drugie - j przy następnym przebiegu pętli for
  // będzie startowało od ostatniej wartości, a nie od początku
  while (a < (b = input[j])) {
   --j;
  }

  // wartość bezwględna taka sama
  if (a == b) {
   output[output.length] = b;
   // output[output.length] szybsze od output.push()...
   --j;
  }
 }

 return output;
}
solve(a);
ready

Revisions

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