Actionscript Optimization Guide

Source: Internet
Author: User
Tags eval execution expression variables resource visibility advantage
Optimized original Marco Lapi, AWTranslated [Special thanks to friends Yang Xin]

In this article, we'll discuss a variety of ways to optimize Actionscript code.
In addition, we also conducted a series of tests for some typical game codes to maximize the performance of the Flash Player.

Introduction to code optimization

In this article, we will show you some flash games that have been optimized by technical means. Code optimization is important because it helps you conserve the resources of your Flash player and make your game more stable in different hardware environments. This paper mainly discusses some problems based on flashplayer6.0, and how to solve them through feasible technical means.

With the release of flashplayer7.0, some technical problems have been solved, and performance has generally improved, however, when writing this article,flashplayer6.0 still has a wide range of applications. So we're still focused on the 6.0 version. -aw speculation: foreign purchases of pirated very few, so many people may not be able to use 7.0, especially those amateur flash designers.

When to optimize

The process of optimizing an existing program is sometimes lengthy and difficult, which is related to the degree of optimization of the original code, so before you invest a lot of time in code optimization, it is important to estimate where you want to modify or replace the code.

The most important part of a game code is the main loop body, which usually executes on every frame of flash and controls the role attributes and important data parameters in the game. For parts other than the main loop body, it may also be a secondary part of the loop, as well as the allocation of too much resources to the core of resources that are more needed.

By accumulating the time that is saved everywhere (perhaps just a few milliseconds each), you will obviously find your SWF running more stable and playing a much stronger game.

Simple and efficient Code

Writing a very concise, callable code (sometimes object-oriented) is a fine piece of work, but it takes years of programming experience. For OOP (object oriented programming, object-oriented programming), some situations simply don't take advantage of it, making it a luxury. Under limited resource conditions (which may be the cause of flash players), more advanced methods, like the one just mentioned, may cause unsatisfactory results.

We are not saying that OOP is not good at programming, but in some cases it seems too extravagant and superfluous. After all, sometimes "traditional methods" can get better results.

In general, OOP is better because it makes code maintenance simpler. But in the latter, you will see that sometimes in order to give full play to flashplayer performance, and not using OOP technology. For example: Dealing with mathematical problems that quickly scroll or compute very complex.

Basic optimization

As soon as we mention code optimization, we immediately associate the improvement of execution speed with the lack of consideration of system resource allocation. This is because today, even the computers that will be eliminated have enough memory to run most of our flash games (128M of RAM is sufficient for most situations, and 512M of RAM is the basic configuration of today's new PCs)

Variable

In a variety of important code optimization methods, there is one: when defining local variables, must be defined with the keyword var , because in the Flash Player, local variables run faster, and in their role outside the scope of the system resources are not consumed.

AW: The VAR variable only has "life" in the curly braces pair, and it's one of those people who think that there's no system-learning programmer that's prone to error:

Awmc.onload = function () {  var aw = 1;} Awmc.onenterframe = function () {//no AW this variable}

A section of non-optimized code:

function dosomething () {mx = m = ar = new Array () for  (y=0 y < i; y++) {for  (x=0 x < mx; x + +) 
  {   i = (y * mx) + x   arr[i] = i     }} return arr}

In this code, the variables that are not declared in the function body (those that are only used within the function) are local variables, which makes these variables slower to be invoked by the player and still consumes system resources when the function completes.

The following are the improved code for the same functionality:

function dosomething () {var mx = var i = var ar = new Array () for  (var y=0 y < i; y++) {for  (var x= 0; x < MX; x + +)  {   var i = (Y * mx) + x   arr[i] = i     }} return arr}

As a result, all variables are defined as local variables, and they can be invoked faster by the player. This is especially important when the function is large (10,000 times) in a circular operation! When a function call ends, the corresponding local variables are destroyed and the system resources they occupy are released.

Onenterframe Events

The Onenterframe event is very useful for game developers, which allows us to run a program quickly and repeatedly according to preset frame frequency (fps). Back in the Flash5 era, this (onenterframe real-time monitoring) is a very popular technique to use such events to control the logic of the machine's opponents, or we can set up such events on each bullet to monitor the collision.

In fact, we do not recommend adding such events to too many moveclip because doing so leads to the emergence of "No Clue Code" (spaghetti Code) and can easily lead to a significant reduction in program efficiency.

In most cases, a single onenterframe event can solve the problem: Use this main loop to perform the actions you need.

Another simple way is to set a suitable frame rate: To know the higher the frame frequency, the more intense CPU resources.

When the frame rate is 25-35 (fps), onenterframe is good enough to perform more complex code, even if your computer is configured to be low. Therefore, in the absence of special requirements, we do not recommend the use of a higher than (FPS) of the frame frequency.

Vector graphs and bitmaps

Before we work with graphics, we must make the right choice. Flash can perfect the vector map and bitmap compatibility, but the vector map and bitmap in the player's performance in essence is completely different.

When we use vector graphs, we need to simplify their shapes as much as possible and remove the redundant endpoints. Doing so will greatly reduce the amount of computation that the player will use to render the vector graph. Another important aspect is the use of lines to minimize and avoid redundant line structures because they directly affect the playback efficiency of Flash.

When the transparency of an instance is less than 100, the playback rate is also affected, so if you find your flash playback rate too slow, pick out these transparent examples!

Then, if you really need to present a more complex scenario, you'd better consider using a bitmap implementation. Although Flash is not the most advantageous to bitmap rendering efficiency (for example, and Flash's "brother" director), but rich visual content rendering can only rely on bitmaps ( and bitmap with the complexity of vector graphics rendering rate is very low ), This is also a lot of block based games widely used in the background of the pixel map as a reason. Incidentally, Flash is supported by both Gif,jpg and PNG, but PNG has an absolute advantage in rendering speed, so we recommend that bitmaps in flash be in PNG format as much as possible.

Visibility of movie clips (MovieClip) [hereinafter MovieClip as MC]

You may often encounter a situation where there is a large number of invisible/on-screen MC waiting to appear (such as maps, characters, and so on) outside the screen in the game.
You know, the player still consumes a certain amount of resources to handle these invisible/on-screen MC, even if they are a single frame, not a playback state.

One of the best solutions is to give these MC a blank frame, and when they don't appear on the screen, you can jump to that frame with the gotoandstop () statement, thereby reducing the player's need for resources.

It is important to remember that in this case, simply setting the visibility property to invisible (_visible = false) is not valid, and the player will continue to allocate resources according to the complexity of the frames in which the MC stays or plays.

Array

Arrays are widely used in a variety of applications and games that need to record data.

A typical example is a block based Flash game, in which a map is sometimes stored in a two-dimensional array that is shaped like a arr[y][x. Although this is a very common method, if you use a one-dimensional array, it can improve the efficiency of the program. Another important way to improve array efficiency is to use a for in loop for the array traversal instead of the traditional for or while loop syntax.
For example:

A piece of code is as follows

for (var i in arr) {if (Arr[i] >) {  //Do some operations}}

Its execution speed is significantly higher than this section of code:

for (var i=0 i<10000; i++) {if (Arr[i] >) {  //Do some operations}}

The efficiency of the former is 30% higher than the latter, and this number is more valuable when your game has to execute this piece of code frames by frame.

Advanced Optimization:

Here we test the efficiency of some common code in the game, and give the result. Some of these ideas refer to some of the individuals or groups mentioned at the end of this article.

We tested on two different models of computers.

ATHLONXP 2.6Ghz Desktop 512M memory, Windows2000pro

P4 2.0Ghz Notebook, Windows XP Home Edition

Each test was divided into three groups, averaging the final results.

The result unit of the test is "millisecond", reflecting the execution time of the code. Obviously, the smaller the number, the better the performance of the code.

All code is compiled by MX2004 to build the Flash6.0 version. Interestingly, we can see the gap compiled by MX and MX2004.

All test details can be seen in this PDF file (AW Note: not translated, very simple PDF document, can be read)

I have summed up the results of the test as follows:

1 for Loop and while loop

Using a while loop will be more efficient than the For loop. However, reading data from an array is the best choice for the in loop style!

Therefore, we do not recommend the use of:

for (var i=0; i<1000; i++) {//Do some action}

and recommended use

var i=-1while (++i < 1000) {//For certain actions}

2 reading data from the array

We found that for-in loops are much more efficient than other loops. See:

arr = []max = 5000//Fill a arrayfor (i=0; i < MAX; i++) {Arr[i] = I}var item = null//for Loopfor (var i=0; i < MA X i++) {item = arr[i]}//for in Loopfor (var i-arr) {item = arr[i]}//while Loopi = -1while (++i < MAX) {item = Arr[i]}

3 writes data to the array (while , for )

You can see that the while loop is slightly dominant.

4 _global( global ) variable with Timeline( time axis ) variable

We speculate that the use of global variables can improve the speed of variable calls, but the effect is not as obvious as expected.

5 single row, multiple row variable assignment

We find that the efficiency of single row variable assignment is much higher than that of multiple lines. Like what:

A = 0b = 0c = 0d = 100e = 100

is less efficient:

A = b = c = 0d = e = 100

6) Variable name addressing

This test reflects the importance of the pre addressing of variable names, especially when it comes to the loop, and must first point to the Ding. This greatly saves the addressing time.

Like what:

var num = Nullt = Gettimer () for (Var i=0 i < MAX; i++) {num = Math.floor (max)-Math.ceil (max)}t1.text = "Always Looku P: "+ (Gettimer ()-T)

You might as well :

t = Gettimer () var floor = Math.floorvar Ceil  = Math.ceilfor (var i=0; i < MAX; i++) {num = floor (max)-Ceil (Max)}

7 Short variable name and long variable name

The shorter the variable name, the higher the efficiency. Given the benefits of long variable names (such as ease of maintenance, for example), it is recommended that you use short variable names in key locations (such as when there is a large number of loops), preferably 1-2 characters.

8 declare variables before and after loops

Before the test, we thought it would be more time-saving to declare variables before the loop, but the test results were not obvious, even the opposite!

Internal Declaration t = Gettimer () for (Var i=0 i < MAX; i++) {var test1 = I}t1.text = "Inside:" + (Gettimer ()-T)//External Declaration t = Gettim ER () var test2for (var i=0 i < MAX; i++) {test2 = i}

9 Use nested IF structure

When a complex conditional expression is used. Breaking them up into nested independent judgment structures is the best solution. The following code we have tested, we found that this effect is significantly improved!

MAX = 20000A = 1b = 2c = -3d = 4var I=maxwhile (i >-1) {if (a = = 1 && b = 2 && c = = 3 && d =  = 4) {  var k = d * C * * b * A}}//the judgment below is more time-saving var i=maxwhile (i > 1) {if (a = = 1) {  if (b = = 2)  {   if (c) = = 3)   {    if (d = = 4)    {     var k = d * C * b * a    }  }}}

Telltarget syntax is compared with "point" syntax

If you start to contact Flash code from Flash5.0, then you will remember that we used "telltarget" to control the MC.

This test shows that using telltarget is more efficient than point syntax. So when necessary, consider using this kind of official, publicly-denied syntax (AW note: The individual feels a little trance and doesn't understand why.) But since the test results are so, it is also feasible ... )

MAX = 10000MC = _root.createemptymovieclip ("Test", 1000) function Test_dot () {var i=max while (-i > 1) {  mc._x = 1 0  mc._y =}}function test_telltarget () {var i=max while (-i > 1) {  telltarget (MC)  {   _x = 10
  _y = Ten  }}}

12) Looking for local variables (This method is compared with the With method)

There are many ways to locate local variables. We found that using with has more advantages than using this!

obj = {}obj.a = 1OBJ.B = 2OBJ.C = 3OBJ.D = 4OBJ.E = 5OBJ.F = 6OBJ.G = 7obj.h = 8obj.test1 = Usethisobj.test2 = Usewithmax = 10000function Usethis () {var i = MAX while (i > 1) {  THIS.A = 1  this.b = 2  this.c = 3  this.d = 4
  THIS.E = 5  this.f = 6  this.g = 7  this.h = 8}}function usewith () {var i = MAX while (i > 1) {with  (this)  {   A = 1   b = 2   c = 3   d = 4   e = 5   f = 6   g = 7   h = 8  }}}

13) Loop Monitor keyboard events

Like the address just mentioned, we achieve a point that is more efficient, such as:

KeyDown = Key.isdown Keyleft = key.left//We re-use if (KeyDown (Keyleft))

Attachment: We have tested the efficiency of the key code and value constants to find that there is not much difference.

Math.floor () method and int ()

This issue has been discussed in the Flashkit forum. Tests show that the old int method is more efficient . This is also reflected in our test results.

eval expression vs . Bracket Syntax

We did not find the obvious difference, unlike the old eval expression, which did not have much of an advantage over the bracket method as we just said.

var mc = eval ("_ROOT.MYMC" + i) var mc = _root["MYMC" + i]//both efficiency is almost

16) involving the MC cycle: The difference betweenAsbroadcaster and circulation

The test reflects that using the Asbroadcaster method can greatly improve the efficiency of the cyclic operation of MC. In our tests, we set up 500 MC, and then tested them to make it clear what time it took.

The traditional cycle type:

MAX = 500SX = 550SY = 330movieclip.prototype.oncustomevent = function () {this.removemovieclip ()}function init () {var I=max var rnd = Math.random while (i >-1) {  var m = _root.attachmovie ("Enemy", "E" +i,i)  m._x = Rnd () * SX  m._y = Rnd () * SY  }}init () function Bench () {var t = Gettimer () var i=max while (i > 1) {  _root["E" +i].oncustomeven T ()} Res.text = "Time:" + (Gettimer ()-T)}

Same effect, broadcast with event (Asbroadcaster)

MAX = 500evtManager = {}asbroadcaster.initialize (evtmanager) SX = 550SY = 330movieclip.prototype.oncustomevent = function () {this.removemovieclip ()}function init () {var i=max var rnd = Math.random while (i >-1) {  var m = _root.attachm Ovie ("Enemy", "E" +i,i)  m._x = Rnd () * SX  m._y = rnd () * SY   Evtmanager.addlistener (M)}}init () function Bench () {var t = Gettimer () evtmanager.broadcastmessage ("oncustomevent") Res.text = "Time:" + (Gettimer ()-T)}

Compile and generate files with MX04 for 6.0 players:

One of the interesting things about MX04 is that the performance of the script compiler improves in many ways. The new compiler has a significant improvement in local, global variable addressing efficiency, and you can find many interesting results in PDF files: Global variable addressing is faster than time axis variables, and nested loops are improved. Almost every code compiled with MX04 is more efficient than the MX version.

AWflasher.com: Why to compile for 6.0, there are a considerable number of users abroad in the use of MX6.0. While 7.0Player is free, upgrading software abroad does not seem like a domestic fire, and something is immediately up to the top. Some of my own guesses.

Conclusion:

We found from these test results that for different requirements, the use of different code, we can greatly improve the execution efficiency of the script. Although we have listed a number of ways to optimize the code here, we need everyone to test and experiment a lot (considering the different needs of everyone). If you want to discuss this kind of problem more deeply. can come to our forum .

AW attached:

Finally translated, I also learned a lot of good things, we can go to the gotoandplay of the official, you can also come to my Blog proposed!

This HTML document can also be saved directly ( browser-file-save ), does not contain any pictures, down to the local can be viewed:



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.