Not easy to use “usePhasedInstantiation”

Published by Manfred Karrer on Wednesday, 23 of March , 2011 at 23:47

Have you ever tried to use usePhasedInstantiation? It is not so easy, as you will see…

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

As I discussed in a previous blog entry, I was wondering why Flex is using a deferred asynchronous execution model. I tried to find out what happens if you change this property.

First I tracked the executed frames and checked out how it behaves with different use cases of Flex applications:
With a simply Flex application with a few random components it was like expected: 1 Frame delay for the whole cycle (3 half frames).
Then i added much more components and also some really heavy weight components like DataGrid, DateChooser or ColorPicker.
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).
At last I measured with our Spreadbetting application 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.

I tried to investigate to change this property to see and measure the effects on performance.
But unfortunately it didn´t had any effect. After stepping into the SDK sources, i found the reason:
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,…).
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.
But to change the LayoutManager is not so easy. 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.

Here are the steps how to do this:

In your MXML Application you use a custom Application class:

[code lang="actionscript3"]

MyApplication defines the custom SystemManager as factoryClass in the "Frame" metadata tag:

[code lang="actionscript3"][Frame(factoryClass="com.test.bootstrap.MySystemManager")]
public class MyApplication extends Application
[/code]

MySystemManager overrides the docFrameHandler method and set MyLayoutManager as implementation class for the ILayoutManager:

[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]

In MyLayoutManager you can bypass the assignment of the usePhasedInstantiation property:

[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]

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

So lets do the tests again with this new setting:
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.
The setup with the more complex Flex components gave a bigger difference in time and of course all was executed in one frame again.
In our CMC application the startup was 400ms faster (2300ms vs. 2700ms).
So 15% faster startup with usePhasedInstantiation set to false in our application startup.

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

What is the conclusion?
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.

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 without the deferred lifecycle as well. Also the technique how to exchange the SystemManager and how the implementation for a LayoutManager is configured, was an interesting learning.

Comments (2)

Category: Actionscript,Flash,SDK

A question of style

Published by Manfred Karrer on Friday, 8 of January , 2010 at 00:03

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 your component.

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?

So the first question is:
How are the styles compiled into your swf file?
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:

[code lang="actionscript3"]
 
[/code]

Here is the content of our simple css:

[code lang="actionscript3"]
Button
{
	color: #990000;
}
.myCustomStyle1
{
	color: #009900;
}
 /*
     some additional styles here...
     like Button.myCustomStyle2
*/
[/code]

That´s what we will use for our example here.

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.

[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]

I only pasted the relevant code, so this is not complete but should give the basic idea.
So what happens here?
(Read more…)

Comments Off on A question of style

Category: Flex,SDK

DataBinding under the hood (part 3): Generated Code

Published by Manfred Karrer on Sunday, 26 of April , 2009 at 00:28

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 swf file

These 2 steps are normally not visible, because the generated code is not stored in your project. If you add the compiler argument -keep (or -keep-generated-actionscript=true) in your compiler settings in Flex Builder, you will see a generated folder inside the src folder containing a lot of Actionscript files.

There are different kinds of files generated:

  • Classes defining the default style for Flex components
  • Classes holding the Resourcebundle properties
  • Classes for embedded skins
  • Classes for Flex Application setup
  • Classes for Flex DataBinding

The style, skin and property files are out of our scope here and has no direct relation to this topic.
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…).

So lets look at our relevant classes for DataBinding (all others has been removed):

generated
(Read more…)

Comments (3)

Category: Actionscript,Flash,Flex

DataBinding under the hood (part 2): Features

Published by Manfred Karrer on Monday, 20 of April , 2009 at 21:31

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…

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:

Curly Brackets in MXML

The most obvious one: Binding a source value to a destination value:

This works also for readOnly properties and static constants. 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.

To add 2 way Binding simply use the curly brackets syntax in both objects crosswise:

[code lang="actionscript3"]


[/code]

Here some code examples for Actionscript and E4X expressions:

[code lang="actionscript3"]
// Method calls and calculations


// Perform string concatenation


// Perform a conditional operation using a ternary operator


// E4X expressions

[/code]

A nice feature which is probably not typically used in your daily work, is the possibility to bind to functions. You can use a function as source for your Binding:
(Read more…)

Comments Off on DataBinding under the hood (part 2): Features

Category: Actionscript,Flash,Flex

DataBinding under the hood (part 1): Performance

Published by Manfred Karrer on Saturday, 18 of April , 2009 at 21:21

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 Performance:
It is clear that such a nice feature has it´s overhead.
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.

Lets have a look to different approaches to set a value from a source to a destination object:

  • Binding in MXML with the curly brackets (or the Bindable tag)
  • Using BindingUtils (or ChangeWatcher) in Actionscript
  • Custom Event dispatching
  • Setting the property directly

I created some tests 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.
Here are the results:

  • Binding in MXML: 412 ms
  • BindingUtils: 188 ms
  • Event dispatching: 146 ms
  • Write property directly: 81 ms

(Read more…)

Comments (4)

Category: Actionscript,Flash,Flex