Peter Halasz - 2009-10-31

Don't know if this is the best place to post a patch? But anyway.

In the current codebase (2.0.2 / rev71), b2Mat22 always does a cos() and a sin() when it is created with no arguments like so:

    new b2Mat22();

which is done throughout Box2D's codebase. This causes much unnecessary overhead. b2Mat22 was coming up in the Flash profiler as a hotspot for me. Not sure if this is why, but it should help all the same.

I've made a simple patch which does not change the functionality of the b2Mat22 class, but should make it faster in its common usage. It also calls Set() rather than duplicating the code.

All this patch does is replace the constructor (and it still works the same way):

public function b2Mat22(angle:Number=0, c1:b2Vec2=null, c2:b2Vec2=null)
{
if (c1!=null && c2!=null){
col1.SetV(c1);
col2.SetV(c2);
} else if (angle==0) {
col1.x = 1;   
col2.y = 1;
} else {
Set(angle);
}
}

And as a diff:

    Index: Source/Box2D/Common/Math/b2Mat22.as
    ===================================================================
    -- Source/Box2D/Common/Math/b2Mat22.as (revision 71)
    +++ Source/Box2D/Common/Math/b2Mat22.as (working copy)
    @@ -32,13 +32,12 @@
     if (c1!=null && c2!=null){
     col1.SetV(c1);
     col2.SetV(c2);
    + } else if (angle==0) {
    + col1.x = 1;   
    + col2.y = 1;
    + } else {
    + Set(angle);
     }
    - else{
    - var c:Number = Math.cos(angle);
    - var s:Number = Math.sin(angle);
    - col1.x = c; col2.x = -s;
    - col1.y = s; col2.y = c;
    - }
     }
    
     public function Set(angle:Number) : void

Peter Halasz

Because of Games.

twitter.com/pengo_au