acos vs array

JavaScript performance comparison

Revision 2 of this test case created by Phil H

Preparation code

<script type="text/javascript">
  var i, j, acosTable = new Array(3601),
      v1, v2, cos;
  for (i = 0; i <= 3600; i += 1) {
    j = -1 + i / 1800;
    acosTable[i] = [j, Math.acos(j)];
  }
//  var bins = 10000;
//  var ratioTable = new Array(bins);
//  for (i=0; i<bins; ++i) {
//    // ratio is y/x which is o/a = tan
//    var angle = atan(Math.exp(i/bins));
//    ratioTable[i] = angle;
//  }
</script>
<script>
Benchmark.prototype.setup = function() {
    v1 = {
      x: ~~ (Math.random() * 11),
      y: ~~ (Math.random() * 11)
    };
    v2 = {
      x: ~~ (Math.random() * 11),
      y: ~~ (Math.random() * 11)
    };
    var angle;
};
</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
acos
// direct compute
angle = Math.acos((v1.x * v2.x + v1.y * v2.y) / (Math.sqrt(v1.x * v1.x + v1.y * v1.y) * Math.sqrt(v2.x * v2.x + v2.y * v2.y)));
pending…
table
// cos
cos = (v1.x * v2.x + v1.y * v2.y) / (Math.sqrt(v1.x * v1.x + v1.y * v1.y) * Math.sqrt(v2.x * v2.x + v2.y * v2.y));

// convert to table value
i = -1;
while (++i <= 3600 && Math.abs(acosTable[i][0] - cos) >= 1 / 1800) {}
angle = acosTable[i][1];
pending…
cubic approximation
// cos
cos = (v1.x * v2.x + v1.y * v2.y) / (Math.sqrt(v1.x * v1.x + v1.y * v1.y) * Math.sqrt(v2.x * v2.x + v2.y * v2.y));

angle = (-0.69813170079773212 * cos * cos - 0.87266462599716477) * cos + 1.5707963267948966;
 
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