Frame Distributed Loop

This is not anything new, but I thought to share it anyway.

It’s the usual problem caused by the fact that the Flash Player is single threaded. Each frame Flash Player executes ActionScript code and renders the screen.
If the execution of the ActionScript code takes longer than the time allocated to execute the frame (for example if you publish a swf at 31 FPS it means that each frame has 1000 ms / 31 frames = 32.25 ms to execute), Flash Player will delay the rendering of the screen, causing a disruption for the user or worst it will crash the player.

An extreme example is when you try and execute the following code (execute at your own risk) :

for (var i:int = 0; i < int.MAX_VALUE; i++)
{
    trace(i);
}

Btw you can find a more detailed explanation here.

So I thought about sharing a little class which can help in splitting a time consuming for…i loop to be executed over multiple frames.

Here you can download my FrameDistributedLoop class       

This is by no mean something you should use straight away if you have a slow for…i loop in your code, you should first find out if you really need to do what you are doing in the loop, optimize the code, think again if the loop is really necessary and then think about using this class.

The class itself is pretty simple, the cool thing is that you can specify the percentage of the frame time to be allocated to execute the loop. For example you can say to use max 1/2 of the frame time to execute the loop, which means that there is still 1/2 of the frame time where the Flash Player can render the screen or execute some other code.

And here there is an example of running a for…i loop like this

for (var i:int = 0; i < int.MAX_VALUE; i++)

and distributing the loop onto multiple frames while adding little stormTroopers to a bitmap :

Get Adobe Flash player

you can notice that, event though we are still executing a long for…i loop, the little stormTroopers keep appearing always at the same speed.

Vizio

This entry was posted in AS3, experiments, Flash. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
blog comments powered by Disqus