Checking all points around a point

JavaScript performance comparison

Test case created by Oliver Caldwell

Info

I wrote a game of life and I check all cells around a cell using eight if statements thousands of times a second.

http://jsfiddle.net/Wolfy87/yfS8q/

I want to optimise this. So I am testing an answer from stack overflow.

http://stackoverflow.com/questions/6167283/efficient-way-to-check-all-points-around-a-given-point

Preparation code

<script>
  var cells = [
   [true, false, true],
   [false, false, true],
   [false, false, false]
  ];
 
  var offsets = [{
   x: -1,
   y: 0
  }, // L
  {
   x: -1,
   y: -1
  }, // TL
  {
   x: 0,
   y: -1
  }, // T
  {
   x: 1,
   y: -1
  }, // TR
  {
   x: 1,
   y: 0
  }, // R
  {
   x: 1,
   y: 1
  }, // BR
  {
   x: 0,
   y: 1
  }, // B
  {
   x: -1,
   y: 1
  } // BL
  ];
 
  var alive = null;
 
  var x = null;
 
  var y = null;
 
  var i = null;
</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
If statements
alive = 0;

for (x = 1; x < 2; x++) {
 for (y = 1; y < 2; y++) {
  if (cells[x - 1][y]) {
   alive++;
  }

  if (cells[x - 1][y - 1]) {
   alive++;
  }

  if (cells[x][y - 1]) {
   alive++;
  }

  if (cells[x + 1][y - 1]) {
   alive++;
  }

  if (cells[x + 1][y]) {
   alive++;
  }

  if (cells[x + 1][y + 1]) {
   alive++;
  }

  if (cells[x][y + 1]) {
   alive++;
  }

  if (cells[x - 1][y + 1]) {
   alive++;
  }
 }
}
pending…
Predefined loop
alive = 0;

for (x = 1; x < 2; x++) {
 for (y = 1; y < 2; y++) {
  for (i = 0; i < offsets.length; i++) {
   if (cells[x + offsets[i].x][y + offsets[i].y]) {
    alive++;
   }
  }
 }
}
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