Low Level Optimizations

JavaScript performance comparison

Revision 2 of this test case created

Info

This jsperf uses optimizations that a compiler can do with compiled languages like C/C++.

When working with animations (canvas, webgl), we need to calculate a lot of positions, triangles and things like this. This types of calculations occur many times per second, so would be great to see performance improvements in this area.

Preparation code

<script>
  var testLen = 1800
    , angle = Math.PI/180;
</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
inline
var x = 10
  , y = 0
  , angle = Math.PI/180
  , tx = 0
  , ty = 0;

while (testLen--) {
  tx = x;
  ty = y;
  x = tx * Math.cos(angle) - ty * Math.sin(angle);
  y = tx * Math.sin(angle) + ty * Math.cos(angle);
}



 
pending…
procedural
var x = 10
  , y = 0;

function rotateX(x, angle) {
  return x * Math.cos(angle) - y * Math.sin(angle);
}

function rotateY(y, angle) {
  return x * Math.sin(angle) + y * Math.cos(angle);
}

while (testLen--) {
  x = rotateX(x, angle);
  y = rotateY(y, angle);
}
pending…
procedural with global values
var x = 10
  , y = 0
  , tx = 0
  , ty = 0;

function rotate() {
  tx = x;
  ty = y;
  x = tx * Math.cos(angle) - ty * Math.sin(angle);
  y = tx * Math.sin(angle) + ty * Math.cos(angle);
}

while (testLen--) {
  rotate();
}
pending…
procedural with object
var o = {x: 10, y: 0}
  , tx = 0
  , ty = 0;

function rotate(o, angle) {
  tx = o.x;
  ty = o.y;
  o.x = tx * Math.cos(angle) - ty * Math.sin(angle);
  o.x = tx * Math.sin(angle) + ty * Math.cos(angle);
}

while (testLen--) {
  rotate(o, angle);
}
pending…
object oriented
function Obj() {
  this.x = 10;
  this.y = 0;
  this.rotate = function(angle) {
    var tx = this.x, ty = this.y;
    this.x = tx * Math.cos(angle) - ty * Math.sin(angle);
    this.x = tx * Math.sin(angle) + ty * Math.cos(angle);
  }
}

var o = new Obj();

while (testLen--) {
  o.rotate(angle);
}
pending…
object oriented with prototype
function Obj() {
  this.x = 10;
  this.y = 0;
}

Obj.prototype.rotate = function(angle) {
  var tx = this.x, ty = this.y;
  this.x = tx * Math.cos(angle) - ty * Math.sin(angle);
  this.x = tx * Math.sin(angle) + ty * Math.cos(angle);
}

var o = new Obj();

while (testLen--) {
  o.rotate(angle);
}
pending…
inline TypedArray
var array = new Float64Array([10, 0]);

while (testLen--) {
  var tx = array[0], ty = array[1];
  array[0] = tx * Math.cos(angle) - ty * Math.sin(angle);
  array[1] = tx * Math.sin(angle) + ty * Math.cos(angle);
}
 
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