phetsims / dot

A math library with a focus on mutable and immutable linear algebra for 2D and 3D applications.
MIT License
13 stars 6 forks source link

A suggestion to reduce the number of vector allocations in getRotation of Matrix3.js #23

Closed veillette closed 9 years ago

veillette commented 9 years ago

While looking up the source of allocations in charges and fields, a sizable number of them are involved in the rotation of the node (using setRotation (which itself invoke getRotation)).

In any case, if you carry out the math explicitly, you find that getRotation in Matrix3.js

    // angle in radians for the 2d rotation from this matrix, between pi, -pi
    getRotation: function() {
      var transformedVector = this.timesVector2( dot.Vector2.X_UNIT ).minus( this.timesVector2( dot.Vector2.ZERO ) );
      return Math.atan2( transformedVector.y, transformedVector.x );
    },

can be replaced by

    // angle in radians for the 2d rotation from this matrix, between pi, -pi
    getRotation: function() {
      return Math.atan2( this.m10(), this.m00() );
jonathanolson commented 9 years ago

Ah yes, M * v( 1, 0, 1 ) - M * v( 0, 0, 1 ) (homogeneous vectors) distributes to M * v( 1, 0, 0 ). Thanks for catching that!

I'll make the fix shortly, and it should free up a lot of those vector allocations you were seeing.

jonathanolson commented 9 years ago

Fixed in 32a2f0072ffaac161e5071290f1658235638b9bf, forgot to tag it.

Thanks!