Flex performance considerations - apache-flex

What are the main key-points a Flex developer should remember in order to improve performance of Flex applications?
The ones which come to my mind are:
extending ItemRenderers from more lightweight base classes: i.e. UIComponent
using suspendBackgroundProcessing set to true for animations
using ArrayLists instead of ArrayCollections where appropriate.
useVirtualLayout in Spark DataGroups (unfortunately this step requires Scrollers to make this advice effective)
SQLight performance optimizations for AIR apps (transactions etc)
Probably splitting long data processing into different frames? (Never done this though, so I might be mistaken)
What are the key guidelines you try to follow while developing your Flex3/Flex4/AIR applications in order to increase their performance?

It seems to me a lot of people have performance issues w/ itemRenderers. So, my one contribution here to never use binding an itemRenderer. I fix a lot of customer "memory leak" bugs just by rewriting their itemRenderers to use the dataChange event instead of binding.
Beyond that, I second #Wade Mueller's comment about avoiding nested containers as much as possible.

Although this is less important with the lighter weight Spark Groups, I always try to keep the number of nested containers to a minimum and set explicit positions/sizes when possible. Complicated UIs with dynamically sized containers nested within one another cause a ton of (usually unnecessary) measuring to have to occur. This often results in huge lags when switching between views.

My list:
use local vars instead of global as much as possible
ActionScript instead of MXML as much as possible
[Bindable] generates tons of code, try to avoid it
P.S. Автор, а ты русский язык знаешь? :)

The main things I consider, in order of importance:
Binding
Creates a lot of extra code, and can cause a serious degradation in performance when bindings are not removed. For example, if you reuse components in an applications, listening functions are active throughout the entire flow of your application, consuming unnecessary memory and CPU cycles. For larger applications consider the BindingUtils class.
Note that you cannot unbind properties bound with curly braces {myVariable}
Validate (invalidate) calls are some of the most expensive calls in Flex. Be careful when using them.
validateNow();
Understand the Flex component lifecycle. Overriding these methods can streamline the instantiation process.
Use Vector objects. More information.
Ints > Numbers. Excellent SO answer.
Some more basic tips:
Do not use expensive operations in loops.
for(var i:int = 0; i < massiveArray.length; i++)
In the case of massiveArray, a very large array, length() might be an expensive operation. Assign var massiveArrayLength:int = massiveArray.length; to improve performance.
http://jacksondunstan.com/ has a wealth of articles on optimizing your code. The man is a genius.
Avoid creating unnecessary variables, as instantiation is expensive. Always reuse variables if possible.
function getComplexValue():int {
var i:int = complexCalculation(); // returns int after calculating
return i;
}
Instead, just return immediately.
function getComplexValue():int {
return complexCalculation();
}
If you have access to it, the Flash Profile perspective is your friend. It's a powerful profiler that can reduce the time involved in optimizing a codebase.

Related

Java Collection - ArrayList and Linkedist

Which is better used for cache based application among Arraylist or
Linkedlist and why?
You'll want to use the ArrayList. More often than not, there is a better alternative to using a LinkedList, though there are scenarios where LinkedLists are the right choice.
Why?
LinkedLists use many small chunks of memory, which ends up offering very poor performance due to cache's utilization of locality.

QML Component loader vs separate file for reusing items

In my application ( QML, QtQuck 1.1, C++ ) I want to reuse some items in my screen.
Generally there are two options ( please let me know if there are more)
1.Use a separate .qml file and put the basic block inside and import in new screen
2.Create a component and use loader to load it.
But I cannot understand which option to use.
Whats the difference between these two options.
Or
which will consume less CPU load?
Thanks!!
Use the first approach unless:
You need to conditionally load QML based on some runtime condition. Note that file selectors are more efficient than Loaders for this purpose, but it might not be possible to use them, depending on your requirements.
You want to avoid loading expensive QML until absolutely necessary (lazy loading).
You should especially be wary of using Loader to load components that are created in large numbers (such as those used as delegates in views), as it doesn't come for free.
To clarify on a part of the answer provided by Mitch:
You should especially be wary of using Loader to load components that
are created in large numbers (such as those used as delegates in
views), as it doesn't come for free.
Using a Loaderas a delegate just to create some other object doesn't make sense except for a very narrow case. You can directly and most definitely should use YourItem {} as a delegate instead. Delaying instantiation in a view delegate in particular is not a very good idea, since that will mess up the view layout, absent the actual item's dimensions which can't be determined without loading it. Even in the case where the Loader is not the top element but nested, it won't be problematic, as QML views only instantiate delegate objects for objects that are in view, if your model has 10k objects it is not like you will have 10k loaders unless they are all in view, which ... won't me much of a view.
Also, if you really need dynamic instantiation, then you will need at least an Item to use as a parent anyway, so the overhead of the Loader becomes negligible and a very good trade-off for the extra flexibility and functionality such as use bindings for the item or to set a dynamic source component. You could do that with an Item but you will have to implement it yourself, and in the end it will end up with larger overhead than Loader.
The CPU time for either of the approaches will not make a difference. Now if you are dynamically creating lots of objects manually, you definitely neither need nor should be using loaders. And not because of the CPU time, but because of memory usage - QML objects are memory hogs, a few thousand objects of medium complexity will likely run you into serious trouble on a 32bit build, especially on a mobile device. Even an empty, non visible QtObject is like 160 bytes. On top of that JS garbage collection is pretty much a joke when it comes to releasing resources, it will do fine on reusing. If you for example create 1 GB of visual items, then delete them and force garbage collection, you will only get a tiny fraction of that memory back, but if you create the objects again, memory usage will be pretty much the same +/- a few megabytes.
In short, in separate .qml file put global component wich you will include and use in different files.
Create component in same file if you will use it only in one file.
Also it depends on the size and complexity of the component. Big and complex component preferably place to separate file.
Compiling faster when all code in one file, but development faster when everything in their place.

Should I use only one Ractive instance or many?

I'm building a mobile app that have many panels and I was wondering if it's a good idea (in regards of performance, memory use, code size and ease of maintainability) to have one Ractive instance by panel or if it's preferable to have only one Ractive instance for the whole application? I'm leaning towards many instances for ease of maintainability but I really don't know how it will affect performance and memory use.
The overhead for creating additional instances is very small - it's only really if you're creating hundreds or thousands of instances (whether directly, or as inline components) that you might find you need to optimise things.
So in general I'd advise writing the application in the way that's most maintainable. If you did find that performance was a problem, then depending on the nature of your app you might find a happy medium between having a single instance for the entire thing, and dividing it too finely.

AS3 large game performance degradation over time

I'm currently working on a very large Flash platformer game (hundreds of classes) and dealing with an issue where the game slowly grinds to a halt if you leave it on for long enough. I didn't write the game and so I'm only vaguely familiar with its internals. Some of the mysterious symptoms include,
The game will run fine for a determinate amount of time (on a given level) when all of a sudden it will exponentially start leaking memory.
The time it takes for the game to hit the point where it leaks exponentially is shorter when there's more sprites on the screen.
Even when nothing is being visibly rendered to the screen, the game slows down.
The game slows down faster with more frequent sprite collisions.
Completely disabling the collision code does slow down the degradation but doesn't prevent the game from eventually dropping frames.
Looking at the source and using Flex profiler, my prime suspects are,
There are many loitering objects, especially WeakMethodClosure, taking up large amounts of memory.
The program makes extremely extensive use of weak event listeners (dozens dispatched per frame).
BitmapData is being copied every time a new sprite is created. These are 50x50 pixel sprites that spawn at about 8 sprites per second.
I know it's next to impossible to tell me the problem without seeing the source, so I'm just looking for tidbits that might help me narrow this down. Has anybody experienced this evasive performance degradation in their own projects? What was the cause in your case?
I recently completed a optimization of an large project.
And I can give you some architectural advices:
Main principle – try do as little as possible function / events calls
Get rid off all but one
onEnterFrame / onInterval / onTimer cycles. Do everything you
need in one general event call.
You probably will need a lot of static arrays for storing processed object
references.
Do your graphics / render stuff also in one main loop
Try use big (probably prerendered) canvases instead of small sprites / bitmaps.
Usually it usable for backgrounds. But also working good for a smaller objects
(like trees, platforms, etc)
Rid off small bitmap resources, assemble it to one tile-sheet and draw your stuff
directly from it, through source–rect property
I hope its helps you!
Memory leaks – such headash.
P.S. Test your game in different browsers, IE – most leaking of all, sometimes it don`t clear memory every after refresh.
Avoid anonymous methods - change them into class level methods.
Use weak reference in addEventListener and/or make sure you remove all the listeners of an object before removing it with removeChild
Make sure you removeChild all the sprites instead of just letting them fly off the screen. Also, if possible, reuse the sprites instead of creating new ones.
You should consider object pooling if you have a lot of creation/destruction going on, especially with heavy objects like bitmapdata.
see Object Pool class
Sounds like you need to profile your application to see what is happening.
This thread had a couple of suggestions, but, ultimately, you will need to just put in code to help determine what is going on.
Profiling ActionScript-3 Code
You may want to see if you can just run some smaller parts over a period of time and see if you see a slowdown.
You may want to unit test your application, so you can run various parts rapidly, looking for memory leaks.
One framework is: http://asunit.org/, and another is: http://opensource.adobe.com/wiki/display/flexunit/
Unit testing is something I use a great deal for profiling, so you can test at the top level of your game, run it thousands of times, looking for problems, then run each part and see which has problems, and just work your way down. This is a manual process, but if the two ideas in the SO thread listed in the beginning don't help, this may be your best approach.
Are you using too much memory? Or is your cpu usage too high?
First determine if its a memory or processor limit you are hitting. It sounds like the later, seems like there are many objects doing stuff around ... likely those extra sprites aren't being freed well. Look for dependencies among objects / variables / anything in those events, make sure the sprites are removed, pay attention to any handlers of EnterFrame or recurring events.
It sounds far more likely that you are capping out on processor speed than memory. You have to try extra hard to memory cap a Flash application.
Fortunately there are a lot of easy things you can do to keep CPU down...
1) Stringently manage event listeners for everything, especially mouse listeners. Do you have $texas event listeners on all your sprite objects? That could be a problem.
2) Access arrays using int or uint instead of Number. This is huge, and this is one of those backwater Adobe tricks. Accessing array object with int and uint is way faster than Number and if you do a lot of iteration (and it sounds like you do) this could shave precious milliseconds off your frame execution.
3) In the same vein as #2, monitor your math operations and what types you are using for certain operations. The slowest thing you can do in math operations for AS3 is repetitive casting (feeding ints to a function that returns a Number), or performing basic operations like add and subtract on Number instead of int.
The great thing about having a wtfhuge program like this in Flash is that even a minor optimization change could have a major impact on performance. I once toyed with a raytrace engine in AS3 where I declared one extra variable and it killed my FPS from 30 to 23.
Flash has a rather infamous issue (many consider it a bug) that causes event listeners for timers and the ENTER_FRAME event to not get garbage collected, even if they were weakly referenced. So, even though it's good practice to use weakly referenced events, you should still remove all your event listeners when they are no longer needed.

Should I cache instances of frequently accessed classes

New to .net and was wondering if there is a performance gain to keeping an instance of, for example a DAL object in scope?
Coming from the Coldfusion world I would instanciate a component and store it in the application scope so that every time my code needed to use that component it would not have to be instanciated over and over again effecting performance.
Is there any benefit to doing this in ASP.Net apps?
Unless you are actually experiencing a performance problem, than you need not worry yourself with optimizations like this.
Solve the business problems first, and use good design. As long as you have a decent abstraction layer for your data access code, then you can always implement a caching solution later down the road if it becomes a problem.
Remember that any caching solution increases complexity dramatically.
NO. In the multi-tier world of .asp this would be considered a case of "premature optimization". Once a sites suite of stubs, scripts and programs has scaled up and been running for a few months then you can look at logs and traces to see what might be cached, spawned or rewritten to improve performance. And as the infamous Jeff Atwood says "Most code optimizations for web servers will benifit from money being spent on new and improved hardware rather than tweaking code for hours and hours"
Yes indeed you can and probably should. Oftentimes the storage for this is in the Session; you store data that you want for the user.
If it's a global thing, you may load it in the Application_Start event and place it somewhere, possibly the HttpCache.
And just a note, some people use "Premature Optimisation" to avoid optimising at all; this is nonsense. It is reasonable to cache in this case.
It is very important to do the cost benefit analysis before caching any object, one must consider all the factors like
Performance advantage
Frequency of use
Hardware
Scalability
Maintainability
Time available for delivery (one of the most important factor)
Finally, it is always useful to cache object which are very costly to create or you are using very frequently i.e. Tables's Data (From DB) or xml data
Does the class you are considering this for have state? If not, (and DAL classes often do not have state, or do not need state), then you should make it's methods static, and then you don't need to instantiate it at all. If the only state it holds is a connection string, you can also make that property field a static property field, and avoid the requirement of instantiating it that way.
Otherwise, take a look at the design pattern called Flyweight

Resources