Search code examples
actionscript-3recycle

Is it faster to reset a collection of properties or create a new instance?


I have a Matrix which I recycle and use for drawing DisplayObject instances onto a Bitmap.

At the moment, I reset the Matrix before I render each item, like this:

_matrix.a = 1;
_matrix.b = 0;
_matrix.c = 0;
_matrix.d = 1;
_matrix.tx = 0;
_matrix.ty = 0;

Would it be better to do the above, or to simply do this?:

_matrix = new Matrix();

Generally I would say the former, however I'm unsure if in the case of Matrix there is some heavy stuff going on for each of those properties that I reset (mathematically).


Solution

  • I think reusing the same instance of Matrix is more efficient than creating a new one every time.

    In fact, creating a new instance is a relatively heavy operation and that's why caches are used: to create a few instances and reuse them instead of creating a high number of instances.

    I run a little benchmark and it confirms my answer:

    var t:Number;
    var i:int;
    var N:int = 10000000;
    
    t = getTimer();
    for (i = 0; i < N; i++) {
        _matrix = new Matrix();
    }
    trace(getTimer()-t); // 7600
    
    
    t = getTimer();
    for (i = 0; i < N; i++) {
        _matrix.a = 1;
        _matrix.b = 0;
        _matrix.c = 0;
        _matrix.d = 1;
        _matrix.tx = 0;
        _matrix.ty = 0;
    }
    trace(getTimer()-t); // 4162
    

    Finally, note that the difference is not that much great and that creating 10000000 new instances takes only 7600 ms, so unless you are creating thousands of matrices per frame, either approach wouldn't have a noticeable impact on performance.


    EDIT:

    Using the method identity will have the advantages of both approaches (simplicity and performance):

    t = getTimer();
    for (i = 0; i < N; i++) {
        _matrix.identity();
    }
    trace(getTimer()-t); // 4140