<?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>.:. blog.screenshot.at .:. Flash, Flex, RIA .:. &#187; Mxml</title>
	<atom:link href="http://www.screenshot.at/blog/tag/mxml/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.screenshot.at/blog</link>
	<description>This blog is about Flash, Flex, RIA related stuff</description>
	<lastBuildDate>Mon, 11 May 2015 18:06:51 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Not easy to use &#8220;usePhasedInstantiation&#8221;</title>
		<link>http://www.screenshot.at/blog/2011/03/23/not-easy-to-use-usephasedinstantiation/</link>
		<comments>http://www.screenshot.at/blog/2011/03/23/not-easy-to-use-usephasedinstantiation/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 23:47:48 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[Applications]]></category>
		<category><![CDATA[Asynchronous]]></category>
		<category><![CDATA[Blog Entry]]></category>
		<category><![CDATA[Containers]]></category>
		<category><![CDATA[Cycle 3]]></category>
		<category><![CDATA[Default State]]></category>
		<category><![CDATA[Execution Model]]></category>
		<category><![CDATA[factoryClass]]></category>
		<category><![CDATA[Flex Components]]></category>
		<category><![CDATA[Frame Delay]]></category>
		<category><![CDATA[Frames]]></category>
		<category><![CDATA[Heavy Weight]]></category>
		<category><![CDATA[LayoutManager]]></category>
		<category><![CDATA[Lifecycle]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Mycmc]]></category>
		<category><![CDATA[Random Components]]></category>
		<category><![CDATA[Real World]]></category>
		<category><![CDATA[UsePhasedInstantiation]]></category>
		<category><![CDATA[validateDisplayList]]></category>
		<category><![CDATA[validateProperties]]></category>
		<category><![CDATA[validateSize]]></category>
		<category><![CDATA[World Application]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=581</guid>
		<description><![CDATA[Have you ever tried to use usePhasedInstantiation? It is not so easy, as you will see&#8230; What is usePhasedInstantiation? This is a property at the LayoutManager which is used to decide if the methods for the 3 Lifecycle phases (validateProperties, validateSize and validateDisplayList) are deferred with 3 (half-)frames or if they are all executed synchronously [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Have you ever tried to use <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/managers/LayoutManager.html#usePhasedInstantiation" target="_blank">usePhasedInstantiation</a>? It is not so easy, as you will see&#8230;</p>
<p><span class="hl">What is usePhasedInstantiation?</span><br />
This is a property at the LayoutManager which is used to decide if the methods for the 3 Lifecycle phases (validateProperties, validateSize and validateDisplayList) are deferred with 3 (half-)frames or if they are all executed synchronously in one Frame. So if it is set to true (default state) at an EnterFrame event validateProperties() is called, on the next Render event validateSize() and on the next EnterFrame event validateDisplayList().</p>
<p>As I discussed in a previous <a href="http://www.screenshot.at/blog/2011/01/20/flex-life-cycle/" target="_blank">blog entry</a>, I was wondering why Flex is using a deferred asynchronous execution model. I tried to find out what happens if you change this property.</p>
<p>First I tracked the executed frames and checked out how it behaves with different use cases of Flex applications:<br />
With a simply Flex application with a few random components it was like expected: 1 Frame delay for the whole cycle (3 half frames).<br />
Then i added much more components and also some really heavy weight components like DataGrid, DateChooser or ColorPicker.<br />
Here it took 3 frames, so it seems that there is some code in some of these Flex components which causes additional invalidation cycles (for instance if you call a invalidateProperties method inside of a creationComplete handler you will trigger a new cycle).<br />
At last I measured with our <a href="https://www.mycmc.co.uk/Main.html" target="_blank">Spreadbetting application</a> at CMC Markets. Here it was a bit more difficult because there was more complex stuff going on. I measured the executed frames and time it takes until the application was idle in the login state and waiting for user input. We will compare the results later.</p>
<p>I tried to investigate to change this property to see and measure the effects on performance.<br />
But unfortunately it didn´t had any effect. After stepping into the SDK sources, i found the reason:<br />
It is set to true in the Containers createComponentFromDescriptor method which is called for adding the MXML children inside a Container. So it doesn´t help much if you set it to false at any place in the Application, because it will be overwritten by the adding of the first child at any Container class (Canvas, HBox,&#8230;).<br />
I am not sure if there is a clean solution how to change this default behavior, but for my test case it was enough to simply ignore the value passed into the setter method in the LayoutManager and set the value to false by default.<br />
But to change the LayoutManager is <span class="hl">not so easy</span>. It is setup in the SystemManager and to override this implementation you need to change the SystemManager which can be only defined in an own Application class.</p>
<p>Here are the steps <span class="hl">how to do this:</span></p>
<p>In your MXML Application you use a custom Application class:</p>
<pre>[code lang="actionscript3"]<bootstrap:MyApplication 
  xmlns:mx="http://www.adobe.com/2006/mxml" 
  xmlns:bootstrap="com.test.bootstrap.*" [/code]</pre>
<p>MyApplication defines the custom SystemManager as factoryClass in the "Frame" metadata tag:</p>
<pre>[code lang="actionscript3"][Frame(factoryClass="com.test.bootstrap.MySystemManager")]
public class MyApplication extends Application
[/code]</pre>
<p>MySystemManager overrides the docFrameHandler method and set MyLayoutManager as implementation class for the ILayoutManager:</p>
<pre>[code lang="actionscript3"]public class MySystemManager extends SystemManager {
override mx_internal function docFrameHandler(event:Event = null):void {
  Singleton.registerClass("mx.managers::ILayoutManager",
    Class(getDefinitionByName("com.test.bootstrap::MyLayoutManager")));
  super.mx_internal::docFrameHandler(event);
}
[/code]</pre>
<p>In  MyLayoutManager you can bypass the assignment of the usePhasedInstantiation property:</p>
<pre>[code lang="actionscript3"]public function set usePhasedInstantiation(value:Boolean):void {
  // for simple testing purpose:
  // simply ignore the values coming from Container and
  // set it by default to false
  value = false;

  if (_usePhasedInstantiation != value) {
    _usePhasedInstantiation=value;
    var sm:ISystemManager=SystemManagerGlobals.topLevelSystemManagers[0];
    var stage:Stage=SystemManagerGlobals.topLevelSystemManagers[0].stage;
    if (stage) {
      if (value) {
        originalFrameRate=stage.frameRate;
        stage.frameRate=1000;
      } else {
        stage.frameRate=originalFrameRate;
      }
    }
  }
}
[/code]</pre>
<p>Another interesting detail is that Flex is setting the framerate to 1000 while these phased instantiation is active to speed up the execution (but this could also lead to strange side effects with too fast running animations like we have in our application with a pre-loader animation).</p>
<p>So lets <span class="hl">do the tests again</span> with this new setting:<br />
The simple setup showed that all is executed inside of one frame and the time measured showed a faster startup, but the difference was pretty small.<br />
The setup with the more complex Flex components gave a bigger difference in time and of course all was executed in one frame again.<br />
In our CMC application the startup was 400ms faster (2300ms vs. 2700ms).<br />
So <strong>15% faster startup</strong> with usePhasedInstantiation set to false in our application startup.</p>
<p>To be honest, I was expecting more. Maybe it is related to the fact that at our application startup (until the login screen) there are not many components created.<br />
I also tried to compare the 2 versions after the user has logged in and under heavy load with a lot of modules and windows open. I could not see a distinct difference but that was probably because of the complexity in this setup caused by a lot of network events.<br />
At least i could not see any problems with rendering. The application was not freezing in any state, so the reason why usePhasedInstantiation was introduced to make the startup more fluidly, does not show any effect in our application.</p>
<p><span class="hl">What is the conclusion?</span><br />
It does not improve the startup performance much if this property is changed (15% in our application), but I could imagine, when using a lot of components created all at once at startup time, the difference could be stronger. Maybe there could also be problems with freezing the rendering when setting the flag to false.</p>
<p>Even the result is for our use-case not much improvement, it was interesting to see how it is implemented, and to show that Flex is working fine <span class="hl">without the deferred lifecycle</span> as well. Also the technique how to exchange the SystemManager and how the implementation for a LayoutManager is configured, was an interesting learning.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2011/03/23/not-easy-to-use-usephasedinstantiation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A question of style</title>
		<link>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/</link>
		<comments>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 00:03:02 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[Button Color]]></category>
		<category><![CDATA[Button Style]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[Constructor]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[Css Code]]></category>
		<category><![CDATA[Css File]]></category>
		<category><![CDATA[Css Files]]></category>
		<category><![CDATA[CSSStyleDeclaration]]></category>
		<category><![CDATA[Custom Components]]></category>
		<category><![CDATA[Definitions]]></category>
		<category><![CDATA[Developers]]></category>
		<category><![CDATA[External Css]]></category>
		<category><![CDATA[Mx]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Null]]></category>
		<category><![CDATA[Selectors]]></category>
		<category><![CDATA[Strange Problems]]></category>
		<category><![CDATA[Style]]></category>
		<category><![CDATA[Swf]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=454</guid>
		<description><![CDATA[If you ever had some strange problems with styles in Flex, you might want to know how styles are internally handled and implemented. Ok this post will not cover too much of all the stuff going on there, but a bit of the basics how styles are finding their way from the css file to [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>If you ever had some strange problems with styles in Flex, you might want to know how styles are internally handled and implemented.<br />
Ok this post will not cover too much of all the stuff going on there, but a bit of the basics <span class="hl">how styles are finding their way</span> from the css file to your component.</p>
<p>Lets assume that we have a css file with type selectors and class selectors, a module based application and some custom components which are designed the way that you can use them out of the box and that they can be individually skinned and styled by other developers reusing them. That´s what custom components are for, right?</p>
<p>So the first question is:<br />
<span class="hl">How are the styles compiled into your swf file?</span><br />
Assume that they are defined in an external css file. You know you can compile css files to swf files and load them at runtime or simply compile them into your application at compile time with a simple assignment  like this:</p>
<pre>[code lang="actionscript3"]
<mx:Style source="assets/styles.css"/> 
[/code]</pre>
<p>Here is the content of our simple css:</p>
<pre>[code lang="actionscript3"]
Button
{
	color: #990000;
}
.myCustomStyle1
{
	color: #009900;
}
 /*
     some additional styles here...
     like Button.myCustomStyle2
*/
[/code]</pre>
<p>That´s what we will use for our example here.</p>
<p>In this case the MXML compiler creates a bunch of classes and inserts the css definitions right into a method called from the constructor in the generated Applications class.</p>
<pre>[code lang="actionscript3"]
public function StyleExample() {
	mx_internal::_StyleExample_StylesInit();
}
mx_internal function _StyleExample_StylesInit():void {
	var style:CSSStyleDeclaration;
	// Button
	style = StyleManager.getStyleDeclaration("Button");
	if (!style) {
		style = new CSSStyleDeclaration();
		StyleManager.setStyleDeclaration("Button", style, false);
	}
	if (style.factory == null) {
		style.factory = function():void {
			this.color = 0x990000;
		};
	}
	// myCustomStyle1
	style = StyleManager.getStyleDeclaration(".myCustomStyle1");
	if (!style)
	{
		style = new CSSStyleDeclaration();
		StyleManager.setStyleDeclaration(".myCustomStyle1",
                                           style, false);
	}
	if (style.factory == null)
	{
		style.factory = function():void
		{
			this.color = 0x009900;
		};
	}
	// similar code follows here....
}
[/code]</pre>
<p>I only pasted the relevant code, so this is not complete but should give the basic idea.<br />
So what happens here?<br />
<span id="more-454"></span><br />
A CSSStyleDeclaration is created for the given stylename or class if it´s not already existing in the StyleManager (at a modular application some other application could have already created this style). Then the definitions from the css file (here the color property) are added to the factory function.<br />
It is interesting that the class selectors and type selectors are treated the same way regarding storing the style object in the StyleManager. It is simply the selector name which is used as the key in the _selectors Object (hashtable). Only the &#8220;.&#8221; in the selector name is the visible difference.</p>
<pre>[code lang="actionscript3"]
    public function setStyleDeclaration(
                                selector:String,
                                styleDeclaration:CSSStyleDeclaration,
                                update:Boolean):void
    {
        styleDeclaration.selectorRefCount++;

        _selectors[selector] = styleDeclaration;

        // Flush cache and start over.
        typeSelectorCache = {};

        if (update)
            styleDeclarationsChanged();
    }
[/code]</pre>
<p>The CSSStyleDeclaration has also a defaultFactory which is used if there is no factory defined (no css file). Additionally there is an overrides Object which is used to store styles set at runtime vial setStyle(), but this will not be further considered yet.<br />
This leads us to the next part:<br />
<span class="hl">How should a default style be applied to a custom component?</span></p>
<p>How Flex is handling this? The MXML compiler generates a bunch of style classes:<br />
For instance a style class for the Button:</p>
<pre>[code lang="actionscript3"]
public class _ButtonStyle
{
    public static function init(fbs:IFlexModuleFactory):void
    {
        var style:CSSStyleDeclaration =
                         StyleManager.getStyleDeclaration("Button");
        if (!style)
        {
            style = new CSSStyleDeclaration();
            StyleManager.setStyleDeclaration("Button", style, false);
        }
        if (style.defaultFactory == null)
        {
            style.defaultFactory = function():void
            {
                this.fontWeight = "bold";
                this.paddingTop = 2;
                this.cornerRadius = 4;
                this.textAlign = "center";
                this.verticalGap = 2;
                this.horizontalGap = 2;
                this.skin = mx.skins.halo.ButtonSkin;
                this.paddingLeft = 10;
                this.paddingBottom = 2;
                this.paddingRight = 10;
            };
        }
    }
}
[/code]</pre>
<p>This class is added to the mixins array at the generated _StyleExample_mx_managers_SystemManager class.<br />
The <span class="hl">mixins</span> are a strategy to get injected some code at application startup before anything else is instantiated. It calls the static init method, so it is executed before the actual classes constructor is called.<br />
A similar strategy with a static initializer is used in some classes in the datavisualisation package to pack some default styles into a component, so that there is no dependency that there are some styles assigned to the component from outside.<br />
That´s seems to be a pretty nice way to setup the default style a component needs. If the user of the component wants to set some different styles, it can be applied easily via css, styles set in mxml or at runtime via setStyle (if possible, this should be done in the preInitialize phase to avoid performance penalties).</p>
<p>One thing which should be considered when using styles (specially in a large application with modules) is the fact that the style declarations are stored with the selector name as key in an Object (hashtable). So if 2 developers are using the <span class="hl">same selector name</span> they end up with a conflict that the later instantiated module will use the already created style and not the one which was compiled to the module.<br />
The same applies if you use the same stylename inside one application, the first one used wins.<br />
To get rid of this problem a kind of namespace strategy can be used ([modulename] + &#8220;stylename&#8221;). Unfortunately the Flex framework does not give any support for this problem.<br />
Tell me if you know a more elegant solution!</p>
<div id="gmBFtt" style="border: 1px solid black ! important; margin: 0px ! important; padding: 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; left: 194px ! important; top: 1926px ! important; visibility: visible ! important; display: inline ! important; width: auto; height: auto ! important; position: absolute ! important; text-align: left ! important; z-index: 1410065406 ! important;">
<div style="border-bottom: 1px dotted black ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; padding-bottom: 2px ! important; padding-top: 2px ! important;"><span id="bfconfigButton" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="Language configuration">Lang</span><span id="bfdetectButton" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer;" title="Detect and set language">Detect</span><span id="bflangsSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="From English To German (switch direction)">en&gt;de </span><span id="bfsvcSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="Translation service: Yahoo (switch service)">Yahoo</span><span id="bfclipboardSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: copy ! important;" title="Copy result to clipboard">C</span><img id="bffishImg" style="border: medium none  ! important; margin: 0px ! important; float: none ! important; vertical-align: top ! important; cursor: pointer ! important; display: inline ! important;" title="Click to translate" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAOCAYAAAA8E3wEAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1QUUDyoqJjAqRwAAAN1JREFUOMu1lMkVwyAMBYe0JGpCNUFNVk3k4AUwxPGS+ILxkzX8jyTH/Sfu9nrmJ3cXlnMASyWRPwd2d5XlHCBZn1BthcbRAdxTZQDI8k3mQzg11rhF+QZ9jdNOcQib6GFQYJYgCFucSRf6GsLU6wEY5yubTFqF2yq1vRwr3INXdQUWG+je1pELX4ED1wDyRAR0WfuAA9gloITyvsFMIMgYInYRqF6rO9Sqz9qkO5ilyo0o3YBwJ+6vrdQonxWUQllhXeHcb/wabMPkP2n81ocAIoLZrMqn/4y2RwP8DcQ+d6rT9ATiAAAAAElFTkSuQmCC" alt="" /></div>
<div style="background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; width: auto;">MXML</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DataBinding under the hood (part 3): Generated Code</title>
		<link>http://www.screenshot.at/blog/2009/04/26/databinding-under-the-hood-part3-generated-code/</link>
		<comments>http://www.screenshot.at/blog/2009/04/26/databinding-under-the-hood-part3-generated-code/#comments</comments>
		<pubDate>Sun, 26 Apr 2009 00:28:40 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[compiler settings]]></category>
		<category><![CDATA[DataBinding]]></category>
		<category><![CDATA[Flex Compiler]]></category>
		<category><![CDATA[Generated Code]]></category>
		<category><![CDATA[Mixin Classes]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Precompiler]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=230</guid>
		<description><![CDATA[So now lets get our hands dirty and check out the generated code which is created behind the scenes. When you compile a Flex application the compiler runs the compilation in 2 steps: The mxmlc compiler generates a lot of Actionscript classes The compc compiler compiles from the generated classes plus your custom classes the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>So now lets get our hands dirty and check out the <span class="hl">generated code</span> which is created behind the scenes.</p>
<p>When you compile a Flex application the compiler runs the compilation in 2 steps:</p>
<ul>
<li>The mxmlc compiler generates a lot of Actionscript classes</li>
<li>The compc compiler compiles from the generated classes plus your custom classes the swf file</li>
</ul>
<p>These 2 steps are normally not visible, because the generated code is not stored in your project. If you add the compiler argument <em>-keep</em> (or <em>-keep-generated-actionscript=true</em>) in your compiler settings in Flex Builder, you will see a <em>generated</em> folder inside the src folder containing a lot of Actionscript files.</p>
<p>There are different kinds of files generated:</p>
<ul>
<li>Classes defining the default style for Flex components</li>
<li>Classes holding the Resourcebundle properties</li>
<li>Classes for embedded skins</li>
<li>Classes for Flex Application setup</li>
<li>Classes for Flex DataBinding</li>
</ul>
<p>The style, skin and property files are out of our scope here and has no direct relation to this topic.<br />
The classes which are used for setting up a Flex Application are our entry point, but will not be discussed in detail (even it would be very interesting to have a closer look to Mixins, [Frame] metadata tags and all these exotic stuff&#8230;).</p>
<p>So lets look at our <strong>relevant classes</strong> for DataBinding (all others has been removed):</p>
<p><img class="alignnone size-full wp-image-238" title="generated3" src="http://www.screenshot.at/blog/wp-content/uploads/2009/04/generated.gif" alt="generated" width="342" height="190" /><br />
<span id="more-230"></span><br />
The entry-point of our Flex application is <span class="hl">_DBGC_mx_managers_SystemManager</span>.<br />
This class extends SystemManager. The SystemManager is the main class and the first DisplayObject added to the stage. It does a lot of setup stuff.<br />
At the first frame in our MovieClip the preloading is handled. At the second frame the Application (DBGC) is instantiated. In the static info() method the mixins classes are defined. At frame 2 the mixin classes are inited via the static method call init().</p>
<p>The <span class="hl">DBCG</span> class (file: DBCG-generated.as) is our Application class.<br />
Here the MXML components are converted to UIComponentDescriptors which handles the instantiation of these Components.<br />
At initialize() an array of Binding objects are created.<br />
The Binding class use anonymous functions for resolving the source and destination properties.</p>
<pre>[code lang="actionscript3"]
var binding:Binding = new mx.binding.Binding(this,
    function():String
    {
        var result:* = (bindableVO.myBindableProp);
        var stringResult:String = (result == undefined ? null : String(result));
        return stringResult;
    },
    function(_sourceFunctionReturnValue:String):void
    {

        myLabel.text = _sourceFunctionReturnValue;
    },
    "myLabel.text");
[/code]</pre>
<p>The <span class="hl">_DBGCWatcherSetupUtil</span> creates an array of PropertyWatcher objects, setup the relationship for chains and pass the Binding object to the PropertyWatcher.</p>
<pre>[code lang="actionscript3"]
watchers[0] = new mx.binding.PropertyWatcher("bindableVO",
    { propertyChange: true },[ bindings[0] ], propertyGetter);
watchers[1] = new mx.binding.PropertyWatcher("myBindableProp",
    { propertyChange: true },[ bindings[0] ], null);
watchers[0].updateParent(target);
watchers[0].addChild(watchers[1]);
[/code]</pre>
<p>After the basic setup execute() is called on every Binding object.<br />
Here is the complete code:</p>
<pre>[code lang="actionscript3"]
override public function initialize():void
{
 	mx_internal::setDocumentDescriptor(_documentDescriptor_);

	var bindings:Array = _DBGC_bindingsSetup();
	var watchers:Array = [];

	var target:DBGC = this;

	if (_watcherSetupUtil == null)
	{
		var watcherSetupUtilClass:Object = getDefinitionByName("_DBGCWatcherSetupUtil");
		watcherSetupUtilClass["init"](null);
	}

	_watcherSetupUtil.setup(this,
				function(propertyName:String):* {
                                     return target[propertyName];
                                },
				bindings,
				watchers);

	for (var i:uint = 0; i &lt; bindings.length; i++)
	{
		Binding(bindings[i]).execute();
	}

	mx_internal::_bindings = mx_internal::_bindings.concat(bindings);
	mx_internal::_watchers = mx_internal::_watchers.concat(watchers);

	super.initialize();
}

private function _DBGC_bindingsSetup():Array
{
    var result:Array = [];
    var binding:Binding;

    binding = new mx.binding.Binding(this,
        function():String
        {
            var result:* = (bindableVO.myBindableProp);
            var stringResult:String = (result == undefined ? null : String(result));
            return stringResult;
        },
        function(_sourceFunctionReturnValue:String):void
        {

            myLabel.text = _sourceFunctionReturnValue;
        },
        "myLabel.text");
    result[0] = binding;

    return result;
}
[/code]</pre>
<p>So lets jump into the <span class="hl">Binding</span> Class. This is a regular Framework class.<br />
The execute() method is basically applying the source value to the destination. In-between there is a lot of error handling going on, but basically it´s nothing else as reading out a value and setting it to the destination. No event dispatching is included until now.</p>
<p>The setting of the value happens on start-up. If the bindable property changes later, event dispatching comes in.<br />
This happens in the <span class="hl">PropertyWatcher</span> class:<br />
An event handler is added at the source object and the PropertyWatcher is listening for the defined event type. It is invoked with weak reference, so the fact that MXML Bindings cannot be removed will not lead to memory leaks.<br />
The event handler checks if the dispatched PropertyChangeEvent contains the same property name as our PropertyWatcher represents and calls notifyListeners() if the property name matches.<br />
On every Binding object which is registered as listener watcherFired() is called.<br />
And here again the execute() method is responsible for passing the value from the source over to the destination.</p>
<p>The last missing link is the class which dispatch the PropertyChangeEvent.<br />
The <span class="hl">BindableProperty</span> (file: _BindablePropertyVO-binding-generated.as) is the place where this happens.</p>
<pre>[code lang="actionscript3"]
[Bindable(event="propertyChange")]
public function get myBindableProp():String
{
    return this._834029286myBindableProp;
}

public function set myBindableProp(value:String):void
{
    var oldValue:Object = this._834029286myBindableProp;
    if (oldValue !== value)
    {
        this._834029286myBindableProp = value;
        this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this,
                                  "myBindableProp", oldValue, value));
    }
}
[/code]</pre>
<p>Here the gettter/setters are created for our [Bindable] property. The compiler defines &#8220;propertyChange&#8221; as event type &#8211; [Bindable(event=&#8221;propertyChange&#8221;)] and dispatches a PropertyChangeEvent if the value has changed.<br />
If the class containing the bindable property is not a subclass of EventDispatcher the compiler set the classes interface of BindableProperty to IEventDispatcher, adds the methods of IEventDispatcher and uses an instance of EventDispatcher via composition.</p>
<p>Note that this code is only generated when you don´t use custom events in the [Bindable] metadata tag ([Bindable(event=&#8221;myCustonEvent&#8221;)]).</p>
<p>I don´t know how this class is linked into the Application, it has no reference anywhere. I guess the compiler do this job behind the scenes, as well as with the interface classes and some other stuff.</p>
<p>Lets have a look to the <span class="hl">moments when DataBinding is executed:</span></p>
<p>At <strong>Application start-up</strong> the Binding is executed  for the first time.<br />
Here is the call stack (Breakpoint at Binding.execute():</p>
<p><img class="alignnone size-full wp-image-248" title="dbseq1" src="http://www.screenshot.at/blog/wp-content/uploads/2009/04/dbseq1.gif" alt="dbseq1" width="613" height="188" /></p>
<p>Due the fact that the component is not created yet, the Binding fails in a catch Block at wrapFunctionCall() in the Binding class. The catch block is pretty slow, i am wondering why this initial execute() is not prevented? At least the try/catch could be replaced with a check against null  which is much faster then falling into the catch block. I guess in large applications this could noticeable slow down start-up time.</p>
<p>At the time the <strong>component is added to the Application</strong> executeBinding() is called and triggers the second execute().</p>
<p><img class="alignnone size-full wp-image-249" title="dbseq2" src="http://www.screenshot.at/blog/wp-content/uploads/2009/04/dbseq2.gif" alt="dbseq2" width="613" height="321" /></p>
<p>At this point the component is valid but there is only the value passed which is defined in the property declaration. This value is often not set at this momens so it is null.</p>
<p>If you setup your initial value at the <strong>initialize</strong> event a third run will be triggered:</p>
<p><img class="alignnone size-full wp-image-250" title="dbseq3" src="http://www.screenshot.at/blog/wp-content/uploads/2009/04/dbseq3.gif" alt="dbseq3" width="590" height="494" /></p>
<p>You can prevent this if you set the value right at the variable declaration (if possible) and so prevent to trigger DataBindings third round.</p>
<p><span class="hl">Conclusion</span><br />
Finally we are through the basic parts how DataBinding is working behind the scenes. To go further it´s best to step through the generated code and try out different scenarios.<br />
We only have had a look into Binding in MXML. If you use BindingUtils just the code for event dispatching from the [Bindable] metadata tag is created.</p>
<p>The generated code for DataBinding with MXML do a lot of error handling. it´s clear that it has some performance drawbacks but gives the benefit that it is very fault-tolerant. You also should consider that there are a lot of different features and use cases for Binding (functions, expressions, 2-way Bindings,&#8230;) which has to be handled.</p>
<p>For large applications BindingUtils are the better choice and prevents several performance drawbacks, specially at start-up time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2009/04/26/databinding-under-the-hood-part3-generated-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>DataBinding under the hood (part 2): Features</title>
		<link>http://www.screenshot.at/blog/2009/04/20/databinding-under-the-hood-part2-features/</link>
		<comments>http://www.screenshot.at/blog/2009/04/20/databinding-under-the-hood-part2-features/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 21:31:13 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[[Bindable]]]></category>
		<category><![CDATA[Binding tag]]></category>
		<category><![CDATA[BindingUtils]]></category>
		<category><![CDATA[ChangeWatcher]]></category>
		<category><![CDATA[Curly Brackets]]></category>
		<category><![CDATA[DataBinding]]></category>
		<category><![CDATA[E4x]]></category>
		<category><![CDATA[Expressions]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[Metadata Tag]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Ternary Operator]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=175</guid>
		<description><![CDATA[There are many different ways how to use DataBinding. Beyond the obvious ones there are a few more which could be a nice feature for some weird hacks&#8230; Flex gives us 4 different techniques to use DataBinding: Curly Brackets in MXML Binding tag BindingUtils ChangeWatcher Lets have an overview of the possibilities of each technique: [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>There are many different ways how to use <span class="hl">DataBinding</span>.<br />
Beyond the obvious ones there are a few more which could be a nice feature for some weird hacks&#8230;</p>
<p>Flex gives us 4 different techniques to use DataBinding:</p>
<ul>
<li>Curly Brackets in MXML</li>
<li>Binding tag</li>
<li>BindingUtils</li>
<li>ChangeWatcher</li>
</ul>
<p>Lets have an overview of the possibilities of each technique:</p>
<p><span class="hl">Curly Brackets in MXML</span></p>
<p>The most obvious one: <strong>Binding a source value to a destination value:</strong></p>
<p>This works also for <strong>readOnly</strong> properties and <strong>static constants</strong>. You can omit the Bindable metadata tag because the Binding is only triggered at application startup. Static variables are not supported (the Adobe docs are not correct at this). Also Binding to style properties are not supported.</p>
<p>To add <strong>2 way Binding</strong> simply use the curly brackets syntax in both objects crosswise:</p>
<pre>
[code lang="actionscript3"]
<mx:TextInput id="input3" text="{input4.text}"/>
<mx:TextInput id="input4" text="{input3.text}"/>
[/code]
</pre>
<p>Here some code examples for <strong>Actionscript and E4X expressions:</strong></p>
<pre>
[code lang="actionscript3"]
// Method calls and calculations
<mx:Text text="{ Math.round(Number(myTI.text)) * 6 / 7 }" />

// Perform string concatenation
<mx:Text text="Cool stuff for lazy {myTI.text}" />

// Perform a conditional operation using a ternary operator
<mx:Text text="{(isMale.selected) ? 'Mr.' : 'Ms.'} {myTI.text}" />

// E4X expressions
<mx:List dataProvider="{data.item.(@id=='36' || @id=='59').desc}"/>
[/code]
</pre>
<p>A nice feature which is probably not typically used in your daily work, is the possibility to bind to functions. You can use a <strong>function as source for your Binding</strong>:<br />
<span id="more-175"></span>To make this work you have to mark the function with the Bindable metadata tag and define your custom event name. When you dispatch an Event with your selected event name the Binding is triggered and the destination gets the return value of your function.</p>
<pre>[code lang="actionscript3"]

       <!--[CDATA[
              [Bindable (event="checkBoxSelected")]
              private function isSelected():String
              {
                     return cb.selected.toString();
              }
              private function checkBoxSelected():void
              {
                     dispatchEvent(new Event("checkBoxSelected"));
              }
       ]]&gt;
</mx:Script>
<mx:CheckBox id="cb" click="checkBoxSelected()" />
<mx:TextArea id="myTA11" text="{isSelected()}" />
[/code]</pre>
<p>Another way is to use <strong>bindable properties as arguments to the function</strong>. When the property change the function is triggered.</p>
<pre>
[code lang="actionscript3"]
<mx:CurrencyFormatter id="usdFormatter"
        precision="2" currencySymbol="$" alignSymbol="left" />
<mx:TextInput id="myTI10" text="Enter number here" />
<mx:TextArea text="{usdFormatter.format(myTI10.text)}" />
[/code]</pre>
<p>In an <strong>MXML</strong> file, you can make all public properties that you defined as variables usable as the source for data binding by including the <strong>[Bindable] metadata tag in an Metadata block</strong>. This is similar to the [Bindable] tag over the class definition in Actionscript.</p>
<pre>
[code lang="actionscript3"]
<mx:Metadata>
    [Bindable]
</mx:Metadata>
[/code]</pre>
<p>There is only one scenario where the curly brackets in MXML are not enough: If you want to use <strong>multiple sources for a destination</strong>.<br />
If you need this you can move over to <span class="hl">Binding tags:</span></p>
<pre>
[code lang="actionscript3"]
<mx:Binding source="input2.text" destination="myTA3.text" />
<mx:Binding source="input1.text" destination="myTA3.text" />
<mx:TextInput id="input1" />
<mx:TextInput id="input2" />
<!  you can also combine curly brackets with the Binding tag -->
<!--<mx:TextArea id="myTA3" text="{input1.text}" />-->

[/code]</pre>
<p>As we have seen in the <a href="http://www.screenshot.at/blog/2009/04/18/databinding-under-the-hood-part-1-performance/">previous post</a> Binding in <strong>MXML is not the fastest solution</strong>.<br />
Your better choice for writing high performacne applications is  <span class="hl">BindingUtils:</span><br />
You have 2 static methods: BindingUtils.bindProperty and BindingUtils.bindSetter</p>
<pre>
[code lang="actionscript3"]
<mx:Script>
    <![CDATA[
        private function onPreInitialize(event:FlexEvent):void 
        {
            BindingUtils.bindProperty(myText5, "text", myTI5, "text");
        }
        
        private function onPreInitialize2(event:FlexEvent):void 
        {
             BindingUtils.bindSetter(setMyText6, myTI6, "text");
        }
        
        private function setMyText6(value:String):void 
        {
            myText6.text = value;
        }
    ]]&gt;
</mx:Script>
<mx:TextInput id="myTI5"/>
<mx:Text id="myText5" preinitialize="onPreInitialize(event);"/>
<mx:TextInput id="myTI6"/>
<mx:Text id="myText6" preinitialize="onPreInitialize2(event);"/>
[/code]
</pre>
<p>The name of the arguments in the API are a little bit confusing (at least for me).</p>
<pre>[code lang="actionscript3"]
public static function bindProperty(site:Object, prop:String,
            host:Object, chain:Object,
            commitOnly:Boolean = false):ChangeWatcher
[/code]</pre>
<p>The first 2 parameters are the destination object and property name, and the last 2 the source object and property name.</p>
<ul>
<li>site:Object -&gt; destination object</li>
<li>prop:String -&gt; destination property name</li>
<li>host:Object -&gt; source object</li>
<li>chain:Object -&gt; source property name(s)</li>
</ul>
<p>Binding supports changes on every bindable element in the source <strong>chain</strong>. If one element is changing the Binding is triggered.<br />
You can specify the chain as a single String for the name of your property (if there is only one chain element) or as Array of property name Strings for each bindable chain element.</p>
<pre>[code lang="actionscript3"]
// bind to object: user.setting.volume
BindingUtils.bindProperty(myText0, "text", user, ["setting", "volume"]);
[/code]</pre>
<p>But there is <strong>another possibility to set the chain argument</strong>:<br />
You can pass an Object in the form:</p>
<pre>[code lang="actionscript3"]
{ name: propertyName,
  getter: function(host) { return host[propertyName] }
}
[/code]</pre>
<p>This Object must contain the name of the property and a function returning a value, which is normally a getter function for a public bindable property of the source object.<br />
This feature opens interesting possibilities.<br />
The function is basically a wrapper which returns the value of the source. I am not sure at the moment where to use this, but it´s good to know that there is an open door…</p>
<p>When using chains with BindingUtils you can choose if the chain elements in-between are bindable.<br />
If an element in-between is not bindable, no Binding is triggered if this element changes.<br />
This is not the case when you use the chains in MXML. You got a compiler warning and a runtime exception if one of the in-between elements are not marked as bindable.</p>
<p>Here is a code example for using chains:</p>
<pre>[code lang="actionscript3"]

<!-- Chains in MXML -->

public class User
{
    [Bindable]
    public var setting:Setting;
    public function User(setting:Setting)
    {
        this.setting = setting;
    }
}

public class Setting
{
    [Bindable]
    public var title:String = "blabla";
    public function Setting()
    {
        setInterval(function():void {
                     title = int(Math.random()*10000).toString()
                     }, 100);
    }
}
[/code]</pre>
<p>The <span class="hl">ChangeWatcher</span> is the class used inside of BindingUtils. ChangeWatcher implements the event handling and the handling for the chains. BindingUtils are just a more convenience way and adds nearly no overhead compared to use ChangeWatcher directly.</p>
<p>Here are <span class="hl">some additional snippets</span> about DataBinding:<br />
You can use <strong>multiple [Bindable] tags</strong>. Doing this lets you trigger Binding from different events.</p>
<p>When you use Binding in MXML the addEventListener method uses a <strong>weak reference</strong>.<br />
This is important due the fact that <strong>you cannot unbind with the curly brackets syntax</strong>. Without weak reference Binding in MXML would be a potential memory leak.</p>
<p>When using BindingUtils you are responsible for calling the <strong>unwatch()</strong> method on your ChangeWatcher object (a ChangeWatcher object is the return value of BindingUtils.bindProperty). The addEventListener method in the ChangeWatcher is not using weak references, so if you don´t do your housekeeping carefully, this could lead to a memory leak.</p>
<p>In UIComponent there is the method <strong>executeBindings()</strong> which force a trigger to all Bindings on this component. This could help sometimes when a Binding is not firing by it´self correctly, but of course should be taken carefully because it´s probably just healing a symptom not the underlying problem.</p>
<p>When you use the <strong>[Bindable] metadata tag before a class definition</strong>, it only applies to public properties; it does not apply to private or protected properties, or to properties defined in any other namespace. You must insert the [Bindable] metadata tag before a nonpublic property to make it usable as the source for a data binding expression.</p>
<p>The DataBinding reference can be found at <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_1.html" target="_blank">Adobe LiveDocs</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2009/04/20/databinding-under-the-hood-part2-features/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DataBinding under the hood (part 1): Performance</title>
		<link>http://www.screenshot.at/blog/2009/04/18/databinding-under-the-hood-part-1-performance/</link>
		<comments>http://www.screenshot.at/blog/2009/04/18/databinding-under-the-hood-part-1-performance/#comments</comments>
		<pubDate>Sat, 18 Apr 2009 21:21:05 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Adobe LiveDocs]]></category>
		<category><![CDATA[Application Startup]]></category>
		<category><![CDATA[auto-generated code]]></category>
		<category><![CDATA[Benefit]]></category>
		<category><![CDATA[Binding in MXM]]></category>
		<category><![CDATA[BindingUtils]]></category>
		<category><![CDATA[Bottleneck]]></category>
		<category><![CDATA[Closer Look]]></category>
		<category><![CDATA[Curly Brackets]]></category>
		<category><![CDATA[DataBinding]]></category>
		<category><![CDATA[Destination Object]]></category>
		<category><![CDATA[Drawback]]></category>
		<category><![CDATA[Event dispatching]]></category>
		<category><![CDATA[Improvements]]></category>
		<category><![CDATA[Iterations]]></category>
		<category><![CDATA[Medium Applications]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Performance Considerations]]></category>
		<category><![CDATA[Performance Features]]></category>
		<category><![CDATA[Performance Penalty]]></category>
		<category><![CDATA[propertyChange event]]></category>
		<category><![CDATA[Random Value]]></category>
		<category><![CDATA[Rapid Development]]></category>
		<category><![CDATA[Runtime Errors]]></category>
		<category><![CDATA[Tag]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=26</guid>
		<description><![CDATA[DataBinding is one of the favorite features of Flex. It makes development fast and is really nice to use. In the following posts we will have a closer look to some different aspects of DataBinding. Performance Features (beyond the obvious ones) Generated Code under the hood So lets start first with a closer look at [&#8230;]]]></description>
				<content:encoded><![CDATA[<p><span class="hl">DataBinding</span> is one of the favorite features of Flex. It makes development fast and is really nice to use.  In the following posts we will have a closer look to some different aspects of DataBinding. <strong> </strong></p>
<ul>
<li>Performance</li>
<li> Features (beyond the obvious ones)</li>
<li>Generated Code under the hood</li>
</ul>
<p>So lets start first with a closer look at <span class="hl">Performance:</span><br />
It is clear that such a nice feature has it´s overhead.<br />
For small and medium applications this probably will not be even noticeable. The benefit´s for rapid development will knock out the performance considerations. But when you work on larger applications you may come to a point where you have to take care of every possible bottleneck. And the sum of a lot of small improvements will give you a considerable performance boost at the end.</p>
<p>Lets have a look to different approaches to set a value from a source to a destination object:</p>
<ul>
<li>Binding in MXML with the curly brackets (or the Bindable tag)</li>
<li>Using BindingUtils (or ChangeWatcher) in Actionscript</li>
<li>Custom Event dispatching</li>
<li>Setting the property directly</li>
</ul>
<p>I created some <a href="http://www.screenshot.at/blogDownloads/TestDataBinding.html" target="_blank">tests</a> passing a random value from a source to a destination with 10 000 iterations and repeated this tests 10 times to get a good average value.<br />
Here are the results:</p>
<ul>
<li> Binding in MXML: 412 ms</li>
<li> BindingUtils: 188 ms</li>
<li> Event dispatching: 146 ms</li>
<li> Write property directly: 81 ms</li>
</ul>
<p><span id="more-26"></span>So there is a considerable performance penalty when using <strong>Binding in MXML</strong>. For small projects this probably will not be a problem, in large applications where a lot of Bindings are triggered, this could be a noticeable drawback. It could slow down the application startup, when all Bindings are initiated.<br />
A good thing on MXML Binding is that it gives you the highest level of pre defined errorhandling. Because most of the generated code can be checked at compile time, it gives you warnings if you going to mess up something. With BindingUtils the possibility of runtime errors is already higher.<br />
Another plus for MXML is that some features are only supported with MXML Bindings (Actionscript expressions, E4X Expressions,&#8230;).</p>
<p>The difference between <strong>BindingUtils </strong>and <strong>EventDispatching </strong>is not so huge, but in some cases you can gain a bit if you handle it by your own event dispatching.</p>
<p>The fastest way of course is <strong>setting a property directly</strong> and could be your good friend in really performance critical areas. But the support for a loosely coupled architecture is not as good as with the other solutions.</p>
<p>There are some further fine-grained improvements possible when using your own event name instead of the default “<strong>propertyChange</strong>” event. In the Bindable metadata tag you can specify a <strong>custom event name</strong>.</p>
<p>[code lang=&#8221;actionscript&#8221;][Bindable (event=&#8221;myCustomEventName&#8221;)][/code]</p>
<p>Doing this, the Flex Compiler <strong>will not auto-generate code for you</strong>, like it is the case when you use [Bindable] without setting an event name. So you have to write a bit more code and dispatch an Event with the given event name. But doing this you can gain some performance improvements.</p>
<p>Here are the test results:</p>
<ul>
<li> BindingUtils with custom event names ([Bindable (event=&#8221;myCustomEvent&#8221;)]): 150 ms</li>
<li> BindingUtils with the default (&#8220;propertyChange&#8221;) event name ([Bindable]): 188 ms</li>
</ul>
<p>Doesn´t sounds too exciting, but that´s not all:<br />
When you have a large class with a lot of bindable properties the performance gain will grow with the number of properties, because all Binding objects have to be checked if one property in this class will change.</p>
<p>Separating properties with custom event names, will speed up performance again.</p>
<p>The test scenario:<br />
Change 10 different properties in one class with 10 custom events versus changing 10 properties in a class with the default event name (do 10 000 iterations).</p>
<p>Here are the test results:</p>
<ul>
<li>Test Binding with different Event names: 1511 ms</li>
<li>Test Binding with the default &#8220;propertyChange&#8221; event name: 2657 ms</li>
</ul>
<p>So now the difference is quite huge.<br />
Of course to have too much properties in one class is often a result of bad design and should not be the typical use case. But it´s good to know where to tweak if performance issues arise.</p>
<p>Here is the <strong>code you have to write by yourself</strong> if you use <strong>custom events</strong>.<br />
It is basically the same the compiler auto-generates for you when you use [Bindable] without a custom event name.</p>
<pre>[code lang="actionscript3"]
private var _myLabelText:String;
[Bindable(event="myLabelTextChanged")]
public function get myLabelText():String
{
    return _myLabelText;
}
public function set myLabelText(value:String):void
{
    if (_myLabelText !== value)
    {
        _myLabelText = value;
        dispatchEvent(new Event("myLabelTextChanged "));
    }
}
[/code]</pre>
<p>References:<br />
Watch out the great presentation about DataBinding by Michael Labriola: <strong>Diving in the Data Binding Waters</strong><br />
Links: <a href="http://www.digitalprimates.net/author/codeslinger/2008/08/20/360-flex-san-jose-recap/" target="_blank">Slides</a></p>
<p>It´s also worth to have a closer look to the DataBinding reference at <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_1.html" target="_blank">Adobe LiveDocs</a>.</p>
<p>The test project is linked <a href="http://www.screenshot.at/blogDownloads/TestDataBinding.html" target="_blank">here</a>, in the View Source context menu the sources are attached.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2009/04/18/databinding-under-the-hood-part-1-performance/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
