Instance Recycling

From ActionScriptWiki

Jump to: navigation, search

Calling the new operator is very expensive. It is possible to use the same instance of an object over and over again instead of creating new ones.

[edit] Wrong Version

In this example a new Point is created for every iteration of the loop. This is very expensive and not needed.

const n: int = 1024;

for( var i: int = 0; i < n; ++i )
{
	var point: Point = new Point();

	point.x = point.y = Math.random();

	// Do something with "point" ...
}

[edit] Correct Version

The point object does not have to be recreated all the time. One instance of it is enough for the whole loop.

const n: int = 1024;
const point: Point = new Point();

for( var i: int = 0; i < n; ++i )
{
	point.x = point.y = Math.random();

	// Do something with "point" ...
}
Personal tools