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).

Answers


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

Need Your Help

Problems with jquery hide() and show() in internet explorer 9

jquery internet-explorer-9

please try out this simple page: http://www.ynnova.it/ie9bug/tryit.html

dynamically populating drop down box not working with 'spaces'

php jquery drop-down-menu

I have a dynamic drop down box which one the first selection, populates the second drop down from the database.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.