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).
I think reusing the same instance of
Matrixis 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:
Finally, note that the difference is not that much great and that creating
10000000new instances takes only7600 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
identitywill have the advantages of both approaches (simplicity and performance):