<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>alecmce.com &#187; performance</title>
	<atom:link href="http://alecmce.com/category/performance/feed" rel="self" type="application/rss+xml" />
	<link>http://alecmce.com</link>
	<description></description>
	<lastBuildDate>Fri, 18 May 2012 02:54:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>gaia-tween</title>
		<link>http://alecmce.com/animation/gaia-tween</link>
		<comments>http://alecmce.com/animation/gaia-tween#comments</comments>
		<pubDate>Sat, 23 Jul 2011 10:52:38 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[animation]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=1141</guid>
		<description><![CDATA[Today I have pushed the first version of a new open-source tween library to github/alecmce/gaia-tween. I have been working on it for some time, to provide a robust, flexible, extensible alternative to the Greensock stable of tween libraries (TweenMax, TweenLite, etc.). I have several reasons for choosing not to use Greensock libraries for tweening: I [...]]]></description>
			<content:encoded><![CDATA[<p>Today I have pushed the first version of a new open-source tween library to <a href="https://github.com/alecmce/gaia-tween">github/alecmce/gaia-tween</a>. I have been working on it for some time, to provide a robust, flexible, extensible alternative to the Greensock stable of tween libraries (TweenMax, TweenLite, etc.).</p>
<p>I have several reasons for choosing not to use Greensock libraries for tweening:</p>
<ul>
<li>I have great respect for TweenLite, but I have rarely used it in anger. Most of the time, the applications that I work on have some element of pay-to-play, and Greensock has <a href="http://www.greensock.com/licensing/">an unusual license</a> that has put-off at least two employers from using it. I do not want to learn a library that I can only use on some of my projects;</li>
<li>For all the clean code we try to write, Tweening libraries often jar with their funky APIs. I didn&#8217;t want my tweening library to be a statically-referenced black-box of almost unreadable code, I wanted it to have elements with well-defined responsibilities, objects that encapsulate concepts of time, tweens and eases. I wanted to be able to <acronym definition="Test Drive Development">TDD</acronym> these elements and offer my tests for public scrutiny. In short, I wanted my tweening library to feel more like the rest of my code and less like dark magic;</li>
<li>Probably most of all, I wanted to write it because I could, and because I hadn&#8217;t yet.</li>
</ul>
<h2>Speed and Memory</h2>
<div style="text-align: center; margin: auto;">
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_0" width="500" height="375">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2011/07/SpeedDemo1.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2011/07/SpeedDemo1.swf" width="500" height="375">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
<br/><a href="https://github.com/alecmce/gaia-tween/blob/master/demo/gaia/demo/tween/SpeedDemo.as">SpeedDemo.as source</a></div>
<p>In the tests that I have done so far, gaia-tween is fractionally behind TweenLite on speed. However, it is ahead in memory consumption! Currently the strategy for gaia-tween is to instantiate the elements that it needs and pool them indefinitely, so there is no garbage collection taking place, but I am looking to add that in as a future iteration. During tweening, no object is constructed nor destroyed by the tweening engine. Compare the memory profile of the two tween engines, from the SpeedDemo test below (<a href="https://github.com/alecmce/gaia-tween/blob/master/demo/gaia/demo/tween/SpeedDemo.as">SpeedDemo source here</a>):</p>
<h3>gaia-tween memory graph</h3>
<p><img src="http://alecmce.com/wp-content/uploads/2011/07/gaia-tween-memory.jpg" alt="" title="gaia-tween-memory" width="484" height="282" class="aligncenter size-full wp-image-1146" /></p>
<h3>TweenLite memory graph</h3>
<p><img src="http://alecmce.com/wp-content/uploads/2011/07/tweenlite-memory.jpg" alt="" title="tweenlite-memory" width="490" height="281" class="aligncenter size-full wp-image-1147" /></p>
<p>gaia-tween uses considerably less memory to run than TweenLite.</p>
<h2>Structure</h2>
<p>The API challenge was to find the right separation of responsibilities to keep the tween engine extensible without the extender having to do unnecessary work. The key features of this API are:</p>
<ul>
<li>Time is an independent concept from the tweening engine. A Time object is passed into the Tweening engine, which responds to changes in milliseconds-elapsed appropriately;</li>
<li>The ease functions have been simplified so that eases take one parameter &#8211; a proportion between 0 and 1, and return back a proportion between 0 and 1. This should make it easier for custom eases to be implemented;</li>
<li>The duration of a tween, the delay before starting it and any ease that may be applied to it are defined at the moment that a tween is added;</li>
<li>All other definition depends upon the context of the tween, and can be defined in a TweenForm. Currently three different kinds of TweenForms exist: a PropertyTweenForm for performing classic property tweens on objects; a ColorTweenForm for tweening the ColorTranform.color property of a DisplayObject; a MethodTweenForm for defining a method that will take the proportion between 0 and 1.</li>
</ul>
<p>This diagram may help explain the concepts more easily:</p>
<p><img src="http://alecmce.com/wp-content/uploads/2011/07/gaia-tween-explanation.jpg" alt="" title="gaia-tween-explanation" width="500" height="438" class="aligncenter size-full wp-image-1154" /></p>
<p>I have also added a convenience class that does the job of creating the TweenForms for you, <code><a href="https://github.com/alecmce/gaia-tween/blob/master/src/gaia/lib/tween/GaiaTweens.as">GaiaTweens.as</a></code>. This object-pools property tween forms and exposes a simplified API for those who want their tweening engine to keep everything under the hood.</p>
<h2>Examples</h2>
<p>The <code>ColorTweenForm</code> in action (roll-over to trigger):</p>
<div style="text-align: center; margin: auto;">
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_1" width="500" height="375">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2011/07/ColorDemo1.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2011/07/ColorDemo1.swf" width="500" height="375">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
<br/><a href="https://github.com/alecmce/gaia-tween/blob/master/demo/gaia/demo/tween/ColorDemo.as">ColorDemo.as source</a></div>
<p><br/></p>
<p>By passing in a different <code>Time</code> class, timeline animations are possible:</p>
<div style="text-align: center; margin: auto;">
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_2" width="500" height="375">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2011/07/TimelineDemo.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2011/07/TimelineDemo.swf" width="500" height="375">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
<br/><a href="https://github.com/alecmce/gaia-tween/blob/master/demo/gaia/demo/tween/TimelineDemo.as">TimelineDemo.as source</a></div>
</p>
<p>Some issues with time-lining remain, and will be worked on for future improvements to the engine.</p>
<h2>Notices and Signals</h2>
<p>I am a huge proponent of the <a href="https://github.com/robertpenner/as3-signals/wiki">as3-signals</a> library. When <a href="http://robertpenner.com/">Robert Penner</a> originally introduced Signals, I was working on something similar with my friend <a href="http://blog.vizio360.co.uk/">Simone</a>. Since that time I have used Signals in almost every project I have worked on. However, One thing I really want to be able to do is to define a signal that only exposes an <code>addOnce</code> method. I have advocated this but there is clearly a disagreement about the direction that signals should take. So, I have created my own &#8211; simplified &#8211; implementation of signals. For want of a better name, I&#8217;ve called them <a href="https://github.com/alecmce/gaia-tween/tree/master/src/gaia/lib/notice"><code>Notices</code></a>. However, if you are interested in using or trying-out gaia-tween but are committed to using Signals, there is a <a href="https://github.com/alecmce/gaia-tween/tree/signals">signals branch</a> that replaces the Notices with Signals.</p>
<h2>Feedback</h2>
<p>I have produced this for my work at <a href="http://www.gaiaonline.com/">Gaia Interactive</a>, but Gaia have agreed to it being released because we would greatly appreciate feedback about it so that it can be improved. Please comment on API decisions, code implementations, feature requests, and so on. The more feedback I get, the more likely I can produce a robust, scalable alternative to the Greensock tweening stable. Or of course, you could fork the library and help improve it more directly!</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/animation/gaia-tween/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Invalidation Manager</title>
		<link>http://alecmce.com/as3/invalidation-manager</link>
		<comments>http://alecmce.com/as3/invalidation-manager#comments</comments>
		<pubDate>Thu, 12 Aug 2010 06:45:27 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=961</guid>
		<description><![CDATA[Introduction Invalidation is a pattern employed to solve problems where updating a model&#8217;s data may happen multiple times per frame, but updating the view&#8217;s rendering should happen only once. When dependencies exist between multiple models this can get complicated and potentially messy. This article looks at a solution to this mess by unifying invalidation logic [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Invalidation is a pattern employed to solve problems where updating a model&#8217;s data may happen multiple times per frame, but updating the view&#8217;s rendering should happen only once. When dependencies exist between multiple models this can get complicated and potentially messy. This article looks at a solution to this mess by unifying invalidation logic into a single manager class.</p>
<p>The purpose of this discussion is not to offer a new class for people to take and use in their libraries so much, though you are welcome, if you should want to. Rather it is to discus a problem and my solution. Hopefully some people will learn something from reading it, and hopefully I will learn something by getting feedback about it!</p>
<h2>The Invalidation Pattern</h2>
<p>Consider the following simple implementation for drawing a coloured circle:</p>
<pre class="brush: as3; title: ; notranslate">
public class Circle extends Sprite
{

	private var _color:uint;
	private var _radius:Number;

	public function get color():Number { return _color; }
	public function set color(value:Number):void
	{
		_color = value;
		resolve();
	}

	public function get radius():Number { return _radius; }
	public function set radius(value:Number):void
	{
		_radius = value;
		resolve();
	}

	private function resolve():void
	{
		graphics.clear();
		graphics.beginFill(_color);
		graphics.drawCircle(0, 0, _radius);
		graphics.endFill();
	}

}
</pre>
<p>The problem here is that if in one frame I changed both the radius and the color, the resolve() function would be called twice. Though not a problem in this case, it could be if the resolve() function involved a lot of complex logic.</p>
<p>The invalidation pattern resolves it this way:</p>
<pre class="brush: as3; title: ; notranslate">
public class Circle extends Sprite
{

	private var _color:uint;
	private var _radius:Number;

	public function get color():Number { return _color; }
	public function set color(value:Number):void
	{
		_color = value;
		invalidate();
	}

	public function get radius():Number { return _radius; }
	public function set radius(value:Number):void
	{
		_radius = value;
		invalidate();
	}

	public function invalidate():void
	{
		... at some future point of my choosing, trigger resolve() ...
	}

	public function resolve():void
	{
		graphics.clear();
		graphics.beginFill(_color);
		graphics.drawCircle(0, 0, _radius);
		graphics.endFill();
	}

}
</pre>
<p>Often in AS3, the invalidate() function looks like this:</p>
<pre class="brush: as3; title: ; notranslate">
public function invalidate():void
{
	addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

private function onEnterFrame(event:Event):void
{
	removeEventListener(Event.ENTER_FRAME, onEnterFrame);
	resolve();
}
</pre>
<p>It is a good pattern that solves the problem of multiple resolve() calls. The actual mechanism contained inside invalidate() which causes resolve() to be called once at a convenient point is unimportant. For this sort of structure, this simple implementation does the job.</p>
<h2>Where The Invalidation Pattern Becomes Complicated</h2>
<p>Imagine that you have two classes: a line, and a circle, the intersection of which defines two circular segments. In fact, don&#8217;t imagine: look at this:</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_3" width="640" height="480">
      <param name="movie" value="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/08/CircleSegmentFromCircleAndLine11.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/08/CircleSegmentFromCircleAndLine11.swf" width="640" height="480">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p>Both the line and circle implementations consist of two points which, on moving, invalidate the their equations. On resolve() the equations are resolved. The segments depend upon the the line and circle; when the line or circle is invalidated, they should be invalidated also.</p>
<p>A mechanism for the segments to know when their definiens (that which defines them) are resolved is required, suggesting that each element conforms to a common interface:</p>
<pre class="brush: as3; title: ; notranslate">
public interface Invalidates
{

	function invalidate():void;

	function get invalidated():Signal;

	function resolve():void;

}
</pre>
<p>and an implementation along these lines:</p>
<pre class="brush: as3; title: ; notranslate">
public class Line implements Invalidates
{

	private var _ax:Number;
	private var _ay:Number;
	private var _bx:Number;
	private var _by:Number;

	private var _invalidated:Signal;

	public function Line()
	{
		_invalidated = new Signal(Invalidates);
	}

	public function get ax():Number { return _ax; }
	public function set ax(value:Number):void
	{
		_ax = value;
		invalidate();
	}

	... missing a few uninteresting methods ...

	public function invalidate():void
	{
		_invalidated.dispatch(this);
	}

	public function resolve():void
	{
		... resolve the line ...
	}

}

public class Segment implements Invalidates
{
	private var _line:Line;
	private var _circle:Circle;

	... missing the constructor ...

	public function get line():Line { return _line; }
	public function set line(value:Line):void
	{
		_line = line;
		_line.invalidated.add(onInvalidated);
	}

	... missing a few uninteresting methods ...

	private function onInvalidated(definien:Invalidates):void
	{
		invalidate();
	}

	public function resolve():void
	{
		_line.resolve();
		_circle.resolve();

		... the rest of the resolution ...
	}
}
</pre>
<p>The problem here is the same problem that led us to consider the Invalidation Pattern in the first place: namely, that the Line&#8217;s resolve() method is going to get called a lot. Sure, we can pack the methods with lots if calls like:</p>
<pre class="brush: as3; title: ; notranslate">
private function invalidate():void
{
	if (_isInvalidated)
		return;

	_isInvalidated = true;
	invalidate();
}

public function resolve():void
{
	if (!_isInvalidated)
		return;

	_isInvaldiated = false;
	_line.resolve();
	_circle.resolve();

	... the rest of the resolution ...
}
</pre>
<p>However, it starts to feel like the classes are consumed with handling the invalidation management, rather than with what should be their single responsibility of properly modelling the geometrical entities for which they are named.</p>
<p>An important feature of this implemenation is that it guarantees that the Line&#8217;s and Circle&#8217;s resolve() methods are called before the sgement resolves. If B depends on A, then A must resolve before B resolves. This is a key feature of the Invalidation Manager, below.</p>
<h2>Managing Invalidation</h2>
<p>The current <a href="http://github.com/alecmce/as3geometry">as3geometry</a> library attempts to solve the problem of invalidation using the <a href="http://github.com/alecmce/as3geometry/blob/master/src/alecmce/invalidation/InvalidationManager.as">InvalidationManager.as</a> class.</p>
<p>The Invalidation Manager handles classes that satisfy the <a href="http://github.com/alecmce/as3geometry/blob/master/src/alecmce/invalidation/Invalidates.as">Invalidates.as</a> interface. Invalidates objects can be registered to the InvalidationManager, and dependencies can be established. As this happens, objects are categorized into <em>tiers</em>.</p>
<p>Initially, since every object is independent of each other when registered, newly registered elements are considered in tier 0. However, if a dependency is established such that B depends on A, B is put into the tier above A, so if A is in tier 0, B is in tier 1. If then C depends on B, since B is already in tier 1, C goes into tier 2.</p>
<p>The utility of the tiers comes from the fact that all objects in tier 0 are independent of each other and may be resolved in any order. Tiers are resolve in ascending order, ensuring that any object that is depended upon is resolved before any object which depends on it.</p>
<p>The problem with this approach comes when, for example, A depends on B depends on C already so they have the following tiers:</p>
<p><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/08/diagram11.png" alt="" title="diagram1" width="236" height="84" class="aligncenter size-full wp-image-962" /></p>
<p>Then, if I have another object D already in tier 3, and define that B depends on D, I must move B to tier 4 and therefore also move C to tier 5.</p>
<p><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/08/diagram21.png" alt="" title="diagram2" width="365" height="75" class="aligncenter size-full wp-image-963" /></p>
<p>Circularity presents an interesting problem within this system. If A depends on B depends on C, and then I define that C depends on A, the tier system breaks down. Currently attempting to create a circular reference will fail and an error will be thrown.</p>
<p>In order to keep the InvalidationManager clean, it does not actually handle when it resolves, but instead dispatches a signal when it has elements that require resolution. In the <a href="http://github.com/alecmce/as3geometry">as3geometry</a> implementation the <a href="http://github.com/alecmce/as3geometry/blob/master/src/as3geometry/AS3GeometryContext.as">AS3GeometryContext.as</a> wraps the InvalidationManager and hooks it to the player events to so that when invalidation occurs it is resolved in good time.</p>
<p>The Invalidates classes, other than telling the contxt what it has a relationship to and what it does not, no longer contains any code that tries to manage other objects&#8217; invalidations:</p>
<pre class="brush: as3; title: ; notranslate">
public class Line implements Invalidates
{

	private var _ax:Number;
	private var _ay:Number;
	private var _bx:Number;
	private var _by:Number;

	private var _context:InvalidationManagerContext;
	private var _invalidated:Signal;

	public function Line(context:InvalidationManagerContext)
	{
		_invalidated = new Signal(Invalidates);

		// elements that don't depend on other classes  like this don't really need the
		// context stored, but I store it here for consistency, and in case the structure
		// changes
		_context = context;
		context.register(this);
	}

	public function get ax():Number { return _ax; }
	public function set ax(value:Number):void
	{
		_ax = value;
		invalidate();
	}

	... missing a few uninteresting methods ...

	public function invalidate():void
	{
		_invalidated.dispatch(this);
	}

	public function resolve():void
	{
		... resolve the line ...
	}

}

public class Segment implements Invalidates
{
	private var _line:Line;
	private var _circle:Circle;

	private var _context:InvalidationManagerContext;
	private var _invalidated:Signal;

	public function Segment(context:InvalidationManagerContext)
	{
		_invalidated = new Signal(Invalidates);

		_context = context;
		_context.register(this);
	}

	public function get line():Line { return _line; }
	public function set line(value:Line):void
	{
		_line = line;
		_context.addDependency(_line, this);
	}

	... missing a few uninteresting methods ...

	private function onInvalidated(definien:Invalidates):void
	{
		invalidate();
	}

	public function resolve():void
	{
		... just resolve here! this is the big win ...
	}
}
</pre>
<h2>Conclusion</h2>
<p>A benefit to this approach is that Invalidates classes need very little boiler-plate code. The author of an Invalidates class need know only that changes should call invalidate() and that all resolution logic happens in resolve(). Responsibilities are extremely well separated.</p>
<p>The <a href="http://github.com/alecmce/as3geometry">as3geometry</a> implementation wraps the InvalidationManager into an <a href="http://github.com/alecmce/as3geometry/blob/master/src/as3geometry/AS3GeometryContext.as">AS3GeometryContext.as</a> class that has a little more logic than the InvalidationManager, which does not have a mechanism for actually triggering the mass resolution. While the InvalidationManager handles the internal logic set-out above, the AS3GeometryContext handles hooking up the InvalidationManager to the player events.</p>
<p>There is a downside, of course. Currently in <a href="http://github.com/alecmce/as3geometry">as3geometry</a>, the constructor of every class contains a reference to the AS3GeometryContext, and every class stores a reference to it. It is not clear to me that this approach is avoidable, unless the manager is defined as a singleton. <a href="http://www.google.com/search?sourceid=chrome&#038;ie=UTF-8&#038;q=why+are+singletons+bad%3F">There are lots of good reasons why singletons are bad</a>, not least because I might have good reason to have two parallel geometric contexts in one application.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/invalidation-manager/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Fast 2D Arrays/Vectors (and the Game Of Life)</title>
		<link>http://alecmce.com/as3/fast-2d-arrays</link>
		<comments>http://alecmce.com/as3/fast-2d-arrays#comments</comments>
		<pubDate>Sun, 07 Mar 2010 06:01:24 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=757</guid>
		<description><![CDATA[Introduction I was recently looking at an implementation of Conway&#8217;s Game Of Life, and was struck by the way in which the developer had constructed his grid. The Game of Life requires that you construct a two-dimensional array, but Flash does not support 2D arrays natively, so work arounds have to be found. There are [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>I was recently looking at an implementation of <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Conway&#8217;s Game Of Life</a>, and was struck by the way in which the developer had constructed his grid. The Game of Life requires that you construct a two-dimensional array, but Flash does not support 2D arrays natively, so work arounds have to be found. There are slow workarounds, fast workarounds, and very fast workarounds. Of course, for very fast workarounds, we use Vector and target the Flash Player 10.</p>
<p>An example of Conway&#8217;s Game Of Life can be found <a href="#example">below</a>.</p>
<p>I should point out at the start that in these I am using <code>for (var x:int = 0; x < 100; x++)</code> loops. Using <code>while (x--)</code> or even <code>while(--x > -1)</code> may well be quicker, but here I am trying to highlight the relative speeds of the data structures that are being looped around, not the loops themselves.</p>
<h2>Slow</h2>
<pre class="brush: as3; title: ; notranslate">
public function generate():void
{
	grid = [];
	for (var x:int = 0; x &lt; 100; x++)
	{
		grid[x] = [];
		for (var y:int = 0; y &lt; 100; y++)
		{
			grid[x][y] = Math.random() &lt; 0.5;
		}
	}
}

public function retrieve(x:int, y:int):Boolean
{
	return grid[x][y];
}
</pre>
<p>This is the slowest good method around. It's undoubtedly good, in that it is readable and concise. It's not so good in terms of speed though, because of the double Array reference that is required to get to the relevant reference. Array lookups are slow, and should be avoided in performance-critical areas.</p>
<h2>Fast</h2>
<pre class="brush: as3; title: ; notranslate">
public function generate():void
{
	grid = [];
	for (var x:int = 0; x &lt; 100; x++)
	{
		for (var y:int = 0; y &lt; 100; y++)
		{
			grid[x * 100 + y] = Math.random() &lt; 0.5;
		}
	}
}

public function retrieve(x:int, y:int):Boolean
{
	return grid[x * 100 + y];
}
</pre>
<p>Instead of putting your 2D grid in a nested array, we can just use a one-dimensional array, and use an expression <code>x * 100 + y</code> within the lookup to differentiate between cells.</p>
<p>If you're targetting the version 9 player still, then this is probably the fastest mechanism you're going to get. (there is probably no need to, <a href="http://www.adobe.com/products/player_census/flashplayer/version_penetration.html">the latest Flash player penetration statistics</a> suggests about 95% adoption in the western hemisphere, and above 90% adoption elsewhere)</p>
<h2>Fast (again, but with Vector)</h2>
<pre class="brush: as3; title: ; notranslate">
public function generate():void
{
	grid = new Vector.&lt;Boolean&gt;(10000, true);
	for (var x:int = 0; x &lt; 100; x++)
	{
		for (var y:int = 0; y &lt; 100; y++)
		{
			grid[x * 100 + y] = Math.random() &lt; 0.5;
		}
	}
}

public function retrieve(x:int, y:int):Boolean
{
	return grid[x * 100 + y];
}
</pre>
<p>Moving to use the FP10 Vector class gives you some great benefits. The Flash Player can be told up-front how big the array is going to be, and it knows the type of element. It is all-round quicker to do it this way. However, this is not the quickest structure we can use!</p>
<h2>Faster</h2>
<pre class="brush: as3; title: ; notranslate">
public function generate():void
{
	shift = 7;
	grid = new Vector.&lt;Boolean&gt;(100 &lt;&lt; shift, true);

	for (var x:int = 0; x &lt; 100; x++)
	{
		for (var y:int = 0; y &lt; 100; y++)
		{
			grid[(x &lt;&lt; shift) | y] = Math.random() &lt; 0.5;
		}
	}
}

public function retrieve(x:int, y:int):Boolean
{
	return grid[(x &lt;&lt; shift) | y];
}
</pre>
<p>By referencing the cell using <code>[x * 100 + y]</code> we get the computer to do a multiplication and an addition. That's pretty quick, but while we consider these two of the most primitive mathematical operations, they are not two primitive calculations for a computer! Instead, we can use <code>[(x << shift) | y]</code> which replaces the multiplication and addition with a bit-shift and a bitwise disjunction. They are about as simple calculations as a computer can make, and the time it gains us is small, but significant if we are working with big grids.</p>
<p>I do not intend to go into the details of bitwise operations here, but for further reading, try <a href="http://en.wikipedia.org/wiki/Bitwise_operation">this Wikipedia article</a>.</p>
<p>Interestingly, if you try this approach with Array, it does not run as quickly as the example labelled 'Fast'. This is because, as <a href="http://jacksondunstan.com/articles/529">Jackson Dunstan</a> and <a href="http://jpauclair.net/2009/12/02/tamarin-part-i-as3-array/">JP Auclair</a> noted, it will leave 'gaps' in the Array (for example no values will be entered in the above Vector for values, 100 - 127. For a Vector of a known size, that is not a performance problem, but Arrays work differently.</p>
<h2>Results Summary</h2>
<div style="text-align: center;"><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/03/Picture-61.png" alt="" title="Chart Showing The Relative Speeds of The Different Approaches" width="502" height="345" /></div>
<p></p>
<p>The results on the horizontal access are milliseconds that it took to iterate through the grid 1000 times. The difference in speed by adopting Vector and the bitwise-shift approach is to cut the calculation time by nearly a quarter. The bigger the grid is, the more this technique becomes useful.</p>
<h2>After-Thought - Game Of Life</h2>
<p>The Game Of Life is a grid structure, in which each cell is a Boolean switch; either 'on' or 'off'. Iteratively, the grid changes, according to a very simple instruction set:</p>
<ol>
<li>Each grid cell's value is determined by the values of the eight adjacent grid cells;</li>
<li>For each cell, If exactly three of those adjacent cells are 'on', then in the next iteration, that cell will be 'on';</li>
<li>For each cell, if two adjacent cells are 'on' then in the next iteration that cell will remain in it's current state;</li>
<li>Otherwise, that cell's value in the next iteration will be set to 'off'.
</ol>
<p>At the edges, either those cells just have fewer neighbours, or the neighbours are thought to 'wrap around' the 2D space, so that the cells' universe resembles a torus in 3D space.</p>
<p>The result of these simple rules is an interesting pattern which is very interesting for a great number of reasons. The example below should show you what I mean. It will run only when the mouse is over the application. Click on it to break the iteration cycle and populate the cells with random data.</p>
<p><a name="example" /></p>
<div style="text-align: center;">

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_4" width="640" height="480">
      <param name="movie" value="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/03/Main21.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/03/Main21.swf" width="640" height="480">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p><a href="http://gist.github.com/324161">source code</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/fast-2d-arrays/feed</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Introducing RacetrackStats v.0.0.1</title>
		<link>http://alecmce.com/as3/introducing-racetrackstats</link>
		<comments>http://alecmce.com/as3/introducing-racetrackstats#comments</comments>
		<pubDate>Tue, 02 Mar 2010 08:08:34 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=741</guid>
		<description><![CDATA[Introduction RacetrackStats is an in-Flash performance profiler that gives real-time feedback about how the code it is contained within is performing. It can be found at GitHub: http://github.com/alecmce/RacetrackStats RacetrackStats is inspired by and seeks to move forward from Mr Doob&#8216;s Stats package (http://code.google.com/p/mrdoob/wiki/stats) In Action Below is the first alpha of RacetrackStats in action. source: [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>RacetrackStats is an in-Flash performance profiler that gives real-time feedback about how the code it is contained within is performing. It can be found at GitHub:</p>
<h3 style="text-align: center;"><a href="http://github.com/alecmce/RacetrackStats">http://github.com/alecmce/RacetrackStats</a></h3>
<p>RacetrackStats is inspired by and seeks to move forward from <a href="http://twitter.com/mrdoob/">Mr Doob</a>&#8216;s Stats package (<a href="http://code.google.com/p/mrdoob/wiki/stats">http://code.google.com/p/mrdoob/wiki/stats</a>)</p>
<h2>In Action</h2>
<p>Below is the first alpha of RacetrackStats in action.</p>
<div style="text-align: center;">

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_5" width="660" height="500">
      <param name="movie" value="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/03/RacetrackStatsDemo2.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/03/RacetrackStatsDemo2.swf" width="660" height="500">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
</div>
<p style="text-align: center;">source: <a href="http://github.com/alecmce/RacetrackStats/blob/master/test/demo/RacetrackStatsDemo.as">http://github.com/alecmce/RacetrackStats/blob/master/test/demo/RacetrackStatsDemo.as</a></p>
<p>The SWF comprises three small animations (from left to right):</p>
<ul>
<li>A mixture of computation and rendering: A simple BitmapData-driven particle system attempting to model smoke using 100000 pixels and a heavy glow filter and blur filter;</li>
<li>Heavy computation: A prime-factorisation algorithm, which computes 24 * 100 prime factor decompositions per frame. As it continues to run, the numbers get larger which leads to heavier calculation cycles;</li>
<li>Extremely heavy rendering: A cycadelic circle pattern that has hundreds of semi-transparent circular sprites moving around and overlapping with each other.</li>
</ul>
<p></p>
<h2>The &#8216;Elastic Racetrack&#8217;</h2>
<p>RacetrackStats attempts to go beyond Mr Doob&#8217;s Stats by measuring how the elastic racetrack is being stretched. The Elastic Racetrack was a phrase coined to describe how the original AVM1 Flash Player segmented each second into frames and attempted to balance the requirements of code, refreshing the screen and doing work like garbage collection. The AVM2 player&#8217;s model is sufficiently similar, that the name remains appropriate.</p>
<h3>Code Execution</h3>
<p>It does this by hooking into the Event.ENTER_FRAME and Event.RENDER events to record when portions of the code start and end. By recording when the ENTER_FRAME starts and when the RENDER starts, the intervening time is taken to be code execution.</p>
<h3>Pre-Render Code Execution</h3>
<p>Commonly this part of the code cycle is almost unused. If you exploit stage.invalidate and Event.RENDER in order for your classes to execute code after the main code execution has completed, then it will be captured here, between the top-priority Event.RENDER and the bottom-priority Event.RENDER calls.</p>
<h3>Rendering</h3>
<p>A problem is, the time between the RENDER ending and the ENTER_FRAME starting is used to draw the screen but if time is left over in which the Flash Player has nothing to do, it will idle during this time also. To counteract this, RacetrackStats attempts to throttle the FlashPlayer so that the application is always running as fast as it can, minimising, or even eliminating that idle time. I call this the &#8220;render&#8221; portion &#8211; the &#8220;Event.RENDER&#8221; event is badly named &#8211; screen rendering happens after the RENDER event has finished.</p>
<h2>Work To Do</h2>
<p>As soon as you add weight like this to an application, the speed at which it runs changes. By measuring the speed, you change the speed. It is the classic scientific paradox. It is mitigated by shrinking down the weight of the stats package as far as possible. At the moment, functionality rather than size is the chief concern, though I have tried to minimize the package by avoiding embedding fonts, and so forth.</p>
<p>I would love to hear what you think about the package, whether positive or negative. I&#8217;d also really appreciate it if you use it in your applications. If you have any problems, questions, queries or comments, please leave a comment below, or open an issue on GitHub.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/introducing-racetrackstats/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Events and Signals &#8211; Performance Tests</title>
		<link>http://alecmce.com/as3/events-and-signals-performance-tests</link>
		<comments>http://alecmce.com/as3/events-and-signals-performance-tests#comments</comments>
		<pubDate>Tue, 26 Jan 2010 08:20:29 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[as3signals]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=673</guid>
		<description><![CDATA[The new as3signals library devised by Robert Penner offers a replacement to the native AS3 event model. One benefit is that signals are more lightweight, and therefore faster. Grant Skinner&#8217;s Performance Harness is a widely accepted library for comparing the speeds of code execution. I found the following results on Mac OS X, Flash Player [...]]]></description>
			<content:encoded><![CDATA[<p>The new <a href="http://github.com/robertpenner/as3-signals">as3signals library</a> devised by Robert Penner offers a replacement to the native AS3 event model. One benefit is that signals are more lightweight, and therefore faster. Grant Skinner&#8217;s <a href="http://www.gskinner.com/blog/archives/2009/04/as3_performance.html">Performance Harness</a> is a widely accepted library for comparing the speeds of code execution.</p>
<p>I found the following results on Mac OS X, Flash Player 10.0.42.34, with a <em>release build</em>.</p>
<p>When an event (signal) is dispatched but nothing is listening for it:</p>
<div style="text-align: center; margin: auto; padding: 10px;"><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/01/results11.jpg" alt="A graph indicating that as3signals events dispatch roughly 5 times faster than native as3 events." width="357" height="262" /></div>
<p>When an event (signal) is dispatched and handled by one method listener:</p>
<div  style="text-align: center; margin: auto; padding: 10px;"><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/01/results21.jpg" alt="A graph indicating that as3signals signals are dispatched and captured at twice the speed of native as3 events." width="357" height="265" /></div>
</p>
<p>The source code for my test methods follows:</p>
<ul>
<li><a href="http://gist.github.com/286640">Dispatching events without listeners</a></li>
<li><a href="http://gist.github.com/286642">Dispatching events with listeners</a></li>
</ul>
<p>If you browse these tests, you will notice that more tests were run than I have displayed above. The graphs above reference results from running the <code>dataEventOptimised</code> and <code>dataSignal</code> methods in each context.</p>
<p>These tests are not scientific. No attempt has been to control for player version, computer version, computer specifications, so on and so forth. You are invited to download and run these tests for yourself. If you do, remember that testing on a <em>release build</em> not a debug build is appropriate, and then please post your results as a comment, particularly if your results differ from my own.</p>
<h2>Updates</h2>
<p>For a comparison with good old fashioned callbacks, please put on your sarcasm snorkel and visit <a href="http://va.lent.in/blog/2010/01/27/omg-as3-signals-are-faster-than-events1">va.lent.in&#8217;s follow up post</a>.</p>
<p>From the <a href="http://groups.google.com/group/as3-signals/browse_thread/thread/3f9a203e6604b0f0?utoken=VwX81i4AAADzSqymN73RML18dAjSp6G6iJqNSdlwl88TjV7a-ukVihfEbSR7To5PnLe8EpnsVXE">as3signals Google Group</a> there was a suggestion that the Flash Player 10.1 might produce different results. Here are my results; they appear to corroborate the earlier results:</p>
<pre class="brush: plain; title: ; notranslate">
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
performancetests.EventsTest (5 iterations)
Player version: MAC 10,1,51,66 (regular)
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
dataEvent                                                  2344   468.80
dataEventOptimised                                         2270   454.00
dataSignal                                                  313    62.60
simpleEvent                                                2755   551.00
simpleEventOptimised                                       2285   457.00
simpleSignal                                                174    34.80
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
performancetests.CapturedEventsTest (5 iterations)
Player version: MAC 10,1,51,66 (regular)
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
dataEvent                                                  2708   541.60
dataEventOptimised                                         2703   540.60
dataSignal                                                 1182   236.40
simpleEvent                                                2724   544.80
simpleEventOptimised                                       2717   543.40
simpleSignal                                               1042   208.40
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
</pre>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/events-and-signals-performance-tests/feed</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Replacing ENTER_FRAME</title>
		<link>http://alecmce.com/as3/replacing-enter_frame</link>
		<comments>http://alecmce.com/as3/replacing-enter_frame#comments</comments>
		<pubDate>Thu, 26 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[as3signals]]></category>
		<category><![CDATA[compiler]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[mxmlc]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=552</guid>
		<description><![CDATA[Today an interesting discussion took place on Twitter, in which I was involved. It caught my attention for a variety of reasons, and I wanted to document the conversation, the problem and the solution here. It started when it was identified that Flash&#8217;s event dispatcher is sub-optimal in performance terms, and revolved around trying to [...]]]></description>
			<content:encoded><![CDATA[<p>Today an interesting discussion took place on Twitter, in which I was involved. It caught my attention for a variety of reasons, and I wanted to document the conversation, the problem and the solution here. It started when it was identified that Flash&#8217;s event dispatcher is sub-optimal in performance terms, and revolved around trying to find a solution.</p>
<h2>Why replace the ENTER_FRAME?</h2>
<p>Every event that is dispatched creates an object. An ENTER_FRAME creates as many objects per second as there are frames. If you have mutliple objects dispatching ENTER_FRAME events, that&#8217;s many objects creating event objects many times per second. Computationally, chains of &#8220;many&#8221; are one of those things you want to avoid. So, can we do better?</p>
<h2>Doing Better</h2>
<p>Robert Penner proposed creating an as3signal and using a MovieClip with two frames to dispatch that signal on each frame. He posted his idea to <a href="http://gist.github.com/243630">this GitHub gist</a>.</p>
<p>One drawback to this approach is that it requires a MovieClip symbol with two empty frames, to which the two event dispatcher methods could be attached. I remembered reading in <a href="http://www.bit-101.com/blog/?p=946">this excellent article by Bit 101</a> how using a [Frame] metadata tag would force your application to have two frames. This seemed to be what Penner needed for his functionality to work correctly, so I came up with <a href="http://gist.github.com/243692">my own GitHub gist</a> which extends the concept. The code is also added &#8216;<a href="#fold">below the fold</a>&#8216;, at the bottom of this article.</p>
<p><em>[Update, after <a href="http://alecmce.com/as3/replacing-enter_frame#comment-24152811">Jackson's comment</a>, below]</em> The idea behind the approach is that a frame-loop is an internal Flash player structure. It sits underneath the AS3 functionality, and so it doesn&#8217;t produce ENTER_FRAME events. By hooking into them we can produce our own iterative &#8216;event&#8217; (Penner proposes using an as3signal), which doesn&#8217;t construct an object each time it is dispatched. It is a lovely idea, and quite distinct from invoking one ENTER_FRAME dispatcher on the root or stage of the application.</p>
<p><em>[Update, after <a href="http://alecmce.com/as3/replacing-enter_frame#comment-24168332">Joa Ebert tweeted test results</a>]</em> Whether this method is superior to the &#8216;one-event ticker&#8217; is open to question. Joa Ebert applied the frameloop concept to AudioBox and found no memory nor performance improvements.</p>
<h2>Background</h2>
<p>It all started today with a statement on Twitter from Robert Penner:</p>
<blockquote><p>Listening to a single #AS3 enterFrame will create over 1000 event instances per minute. <em><a href="http://bit.ly/5A36ZS">@robpenner</a></em></p></blockquote>
<p>In fact, at a decent frame rate, you&#8217;re looking at 1800 event instances per minute. Across the blogosphere and on Twitter, there has been a lot of talk about the cost of object construction in AS3. People are pushing the limitations of the player, and are looking for performance optimisation wherever they can find it. Strategies such as object pooling are becoming mainstream in order to avoid the creation and destruction of objects. In the meanwhile, the internal Flash event model is creating and destroying huge numbers of objects to furnish us with an event model.</p>
<p>At the same time however, there has been a murmur of discomfiture about the state of the event model. (Not that I have much of a voice, but I <a href="http://alecmce.com/opinion/as4-thought-experiment">chimed in to this debate</a> as well!). The most notable result of this murmur was Penner&#8217;s decision to create <a href="http://github.com/robertpenner/as3-signals">as3signals</a>. It is an on-going project to which I have contributed in a small way, and which I whole-heartedly support.</p>
<p>After Penner&#8217;s tweet, the <a href="http://twitter.com/alecmce/flashdevs">#as3 twitterati</a> (please tweet if there are glaring omissions from this list) became very excited indeed.</p>
<p>My initial thoughts led to the idea that maybe the setInterval/setTimeout functions, which are hangovers from AS2 might offer a solution &#8211; perhaps they shortcut the event system? Not only ain&#8217;t it so, they&#8217;re even worse <a href="http://bit.ly/4E1Unk">as this Action Script Viewer deconstruction of the setInterval methods</a> demonstrate.</p>
<p>So what else? Mike Chambers (aka <a href="http://twitter.com/mesh">@Mesh</a>) in conversation with <a href="http://twitter.com/theflashbum">@TheFlashBum</a> pointed towards <a href="http://bit.ly/7NK8hQ">a solution using a &#8216;ticker&#8217;</a>; a single ENTER_FRAME dispatcher, and <a href="twitter.com/bengarney">@bengarney</a> confirmed that <a href="http://bit.ly/8iKdQC">he also uses this technique</a>.</p>
<p>It seems that @scottjanousek and @robpenner had the idea of using the player frameloop (which the solution offered here exploits) at pretty much the same time. (@scottjanousek&#8217;s tweets are protected, but it was reported by <a href="http://bit.ly/4ZdU1Q">this tweet</a>.)</p>
<p>Whether and how this vein of thought will develop is really interesting. It is fascinating how a tweet from one of the best-known ActionScript developers can provoke such a lot of attention from the general community. It is interesting too to see the envelope of what is possible being pushed.</p>
<p><span id="more-552"></span></p>
<h2><a name="fold">FrameLoop Example Source Code</a></h2>
<p>To use this code, you will need the <a href="http://github.com/robertpenner/as3-signals">as3signals</a> library. You will also need to compile through the MXML compiler. I have tested it with the Flex 4 SDK &#8211; if you try and discover that it does not work for other target platforms, please share the information by leaving a comment!.</p>
<h3>Main.as</h3>
<pre class="brush: as3; title: ; notranslate">
package
{
	import org.osflash.signals.Signal;

	import flash.display.Shape;
	import flash.display.Sprite;

	/**
	 * A Main application class that uses the [Frame] MetaData Tag to use the
	 * EventFrameDispatcher class to configure itself. This class contains a
	 * frame signal which is constructed and passed into it by the
	 * EventFrameDispatcher class before init() is called. Application
	 * functionality should be placed in the init() method
	 *
	 * @author Alec McEachran
	 */
	[Frame(factoryClass=&quot;EnterFrameDispatcher&quot;)]
	public class Main extends Sprite
	{
		/** an as3signal that is dispatched on every ENTER_FRAME */
		public var frame:Signal;

		/**
		 * do interesting things in here...
		 */
		public function init():void
		{
			// functionality here...
		}
	}
}
</pre>
<h3>EnterFrameDispatcher.as</h3>
<pre class="brush: as3; title: ; notranslate">
package
{
	import org.osflash.signals.Signal;

	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.utils.getDefinitionByName;

	/**
	 * The EnterFrameDispatcher is injected into the Main class through
	 * the [Frame] MetaData tag.
	 *
	 * The class creates a frame signal. By being injected, two frames are
	 * generated, onto which the frameMethod are attached so that the
	 * frame signal is dispatched on every frame cycle. It then injects this
	 * object into the Main class and calls the Main class's init() method.
	 *
	 * @author Alec McEachran
	 *
	 * based on an idea by Robert Penner @see http://gist.github.com/243630
	 */
	public class EnterFrameDispatcher extends MovieClip
	{
		public var frame:Signal;

		public function EnterFrameDispatcher()
		{
			frame = new Signal();
			addFrameScript(0, frameMethod, 1, frameMethod);

			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			nextFrame();
		}

		private function onEnterFrame(event:Event):void
		{
			removeEventListener(Event.ENTER_FRAME, onEnterFrame);
			init();
			play();
		}

		private function frameMethod():void
		{
			frame.dispatch();
		}

		private function init():void
		{
			var mainClass:Class = Class(getDefinitionByName(&quot;Main&quot;));
			if (mainClass)
			{
				var app:* = new mainClass();
				app.frame = frame;
				addChild(app);
				app.init();
			}
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/replacing-enter_frame/feed</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Constants and Speed</title>
		<link>http://alecmce.com/as3/constants-and-speed</link>
		<comments>http://alecmce.com/as3/constants-and-speed#comments</comments>
		<pubDate>Tue, 17 Nov 2009 11:48:01 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=489</guid>
		<description><![CDATA[A common scenario in coding is to have a constant that you would like to be shared across classes. Defining the constant separately is bad because if you change the constant value in one class it does not get changed in another, and you&#8217;re likely to have a bad dose of debugging. However, defining a [...]]]></description>
			<content:encoded><![CDATA[<p>A common scenario in coding is to have a constant that you would like to be shared across classes. Defining the constant separately is bad because if you change the constant value in one class it does not get changed in another, and you&#8217;re likely to have a bad dose of debugging. However, defining a constant in an external class and referencing it when you need it is bad because it is <em>really slow</em>.</p>
<h2>How Slow?</h2>
<p>Using <a href="http://www.gskinner.com/blog/archives/2009/04/as3_performance.html">Grant Skinner&#8217;s Performance Harness</a> I did a quick test to determine exactly how slow various mechanisms for referencing variables and constants actually are. The results are as follows (based on accessing the variable/constant 10,000,000 times!):</p>
<table style="margin: 0px auto 20px auto; border: 2px solid black;">
<tr>
<td>referencing a local variable</td>
<td style="text-align: right;">46.80 ms</td>
</tr>
<tr>
<td>referencing a member variable</td>
<td style="text-align: right;">44.00 ms</td>
</tr>
<tr>
<td>referencing a member constant</td>
<td style="text-align: right;">48.40 ms</td>
</tr>
<tr>
<td>referencing a static constant in the same class file</td>
<td style="text-align: right;">52.80 ms</td>
</tr>
<tr>
<td>referencing a package constant</td>
<td style="text-align: right;">526.00 ms</td>
</tr>
<tr>
<td>referencing an external static constant</td>
<td style="text-align: right;">550.00 ms</td>
</tr>
</table>
<p>There isn&#8217;t a significant difference between the speed of access of member variables, local variables, or member constants. Perhaps a static constant in the same package is a little slower, but then it would only be defined as <code>public static</code> if it was referenced elsewhere as an external static constant, so it is inevitably a slow choice at some stage.</p>
<p>I tested package constants on the basis that <a href="http://www.danielhai.com/blog/?p=55">this blog I came across</a> suggested that I could get a performance saving by using package constants. This does not appear to be the case; or at least not significantly.</p>
<p style="text-align: center"><a href="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2009/11/performance-tests1.zip">download the test source code</a></p>
<p>Yes, you probably know this already, perhaps with the expception of the package constant, which I had never considered before. However, I&#8217;d never done this test definitively and having recently come across Skinner&#8217;s test harness I thought I&#8217;d be thorough.</p>
<h2>Suggested Solution</h2>
<p>My technique for solving the dilemma of wanting a single source for constants but accessing them quickly is to create a static constant repository, but reference them into member constants in your speed critical classes, as follows:</p>
<p>A constants class:</p>
<pre class="brush: as3; title: ; notranslate">
package example
{
	public class Constants
	{
		public static const MY_CONSTANT:int = 100;
	}
}
</pre>
<p>A class that uses the constant, in time-critical code:</p>
<pre class="brush: as3; title: ; notranslate">
package another
{
	import example.Constants;

	public class TimeCritialCode
	{
		private const MY_CONSTANT:int = Constants.MY_CONSTANT;

		public function timeCriticalLoop():void
		{
			... important stuff referencing MY_CONSTANT ...
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/constants-and-speed/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>

