Actionscript Optimization Guide

Related Tags:

  Original Marco Lapi, aw translation [special thanks to friends Xin Yang] 

  In this article, we will discuss a variety of Actionscript code optimization method. 
  In addition we have for some typical game code to a series of tests to identify the maximum and improve the performance of the Flash player. 

  About Code Optimization 

  In this article, we will show you some of technical means to be optimized flash game.    Code optimization is important because it can help you save flash player resources, but also allows you to the game in different hardware environments running in the more stable.    Based on flashplayer6.0 This paper mainly discusses some of the issues, as well as how technically feasible means to solve them! 

  With the release of flashplayer7.0, some technical problems have been resolved, and the performance in general has increased, but the time of writing this paper, flashplayer6.0 still share a wide range of applications.    Therefore, we mainly concentrated in the 6.0 version.    - Aw guess: very few foreign buying pirated goods, so many people may be too late to use 7.0, especially those who are non-career flash designers. 

  When optimization 

  Optimization of the existing procedures for the process, and sometimes very lengthy and difficult, and the source code of non-optimization level, it is in putting in a lot of time to optimize the code before, the most important thing is to estimate what to do on the code to modify or replace. 

  A game code that is the most important part of the cycle, and under normal circumstances the cycle in the flash of each frame on implementation, and control of the game in the role of an important data attributes and parameters.    For the main part of the outside of the circle, may also be part of a secondary cycle, we should pay attention to is the same whether the distribution to its excessive resources, but not the allocation of resources to those who need the core of the. 

  Through savings accumulated in various places by the time (every possible just a few milliseconds), you will find that their swf obviously running a more stable, and also greatly enhance the sense of the game. 

  Simple and efficient code 

  To write a very simple, can once again call the code (and sometimes is the object-oriented) is a fine work, but it requires years of programming experience.    The OOP (object oriented programming, object-oriented programming), some occasions it is not using the advantage of making it was very extravagant.    In conditions of limited resources (which may be the reasons for the flash player), adopted more advanced methods, such as just mentioned OOP, it may not lead to unsatisfactory results. 

  We are not saying that the OOP programming bad game, but on certain occasions it is too extravagant and unnecessary.    Sometimes, after all, the "traditional methods" managed to get better results. 

  Broadly speaking, using OOP was rather good, because it allows code maintenance easier.    But later, you will see that sometimes in order to give full play to flashplayer performance, instead of OOP techniques.    For example: dealing with rapid calculation of rolling or very complex mathematical problems. 

  Basic optimization 

  A reference to code optimization, we would immediately think of the improved speed of execution, and rarely consider the allocation of system resources.    This is because today, even if the computer will be eliminated, and have enough memory to run most of our flash games (128 M memory sufficient to meet the needs of the majority Moreover, 512 M memory is the new computer the basic configuration) 


  Variables 

  In a variety of important means of optimizing the code, that there is a: In the definition of local variables, must use the var keyword to define, because in the Flash player, local variables faster, but also in their role extraterritorial is not the consumption of the system resources. 

  Aw: Attachment var variable only in the flower only in square brackets on the "life", not personal opinion of the system error-prone programming of a local: 

   AwMC.onLoad = function () (var aw = 1;) awMC.onEnterFrame = function () (/ / variable does not exist aw)  

  A section of non-optimized code: 

   Function doSomething () (my mx = 100 = 100 ar = new Array () for (y = 0, y <my; y) (for (x = 0; x <mx; x) (i = (y * mx) x arr [i] = i))) return arr  

  This code, the statement did not function in those variables (those who function only in the use of variables) for the local variables, which makes these variables were players call the speed more slowly, and in function of time after the implementation of consumption still system resources. 

  Below is a list of the same functions to improve code: 

   Function doSomething () (var mx = 100 = 100 var my var ar = new Array () for (var y = 0, y <my; y) (for (var x = 0; x <mx; x) (var i = (y * mx) x arr [i] = i))) return arr  

  As a result of all the variables are defined to local variables, they can be faster players call.    This is the function of a large number (10,000) cycle operation appears to be particularly important.    When a function call at the end of the corresponding local variables will be destroyed, and the release of their possession of system resources. 

  OnEnterFrame event 

  OnEnterFrame event for game developers who will be very useful, it allows us to rapidly and repeatedly in accordance with the default frame rate (fps) operation for some procedures.    Looking back in the era of Flash5, (onEnterFrame real-time monitoring) is a very popular technology, the use of such events to control the opponent's logic game machines, or we can set up a bullet to monitor such incidents bullets collisions. 

  In fact, we do not recommend adding to the excessive MoveClip such incidents, because doing so will lead to "no clue yards (spaghetti code)," the emergence of procedures and easily lead to decreased efficiency. 

  In most cases, in a separate incident an onEnterFrame problem can be solved: the cycle with this one you need to carry out the operation. 

  Another simple approach is to set up an appropriate frame rate: To know that the higher the frame rate, the more tension CPU resources. 

  In the frame rate of 25-35 (fps) between, onEnterFrame good enough to implement more complex code, even if your computer configuration lower.    Therefore, in the absence of special requirements of the occasion, we do not recommend the use of higher than 60 (fps) frame rate. 

  Vector and bitmap 

  In dealing with graphics, we must make the right choices.    Flash can vector and bitmap compatible with a perfect, but vector and bitmap in the player's performance in real terms is completely different. 

  When used in the vector, we have to streamline their shape, as far as possible, get rid of the endpoint.    This will greatly reduce the players showed vectors to be used for the calculation.    Another important aspect is the use of lines to minimize and avoid redundant Chen's line structure, as they will directly affect the efficiency of the flash player. 

  When a less than 100 examples of transparency, will be broadcast on the impact velocity, so if you find yourself in the Flash player rates too slowly, and go to single out examples of these transparent Come! 

  Well, if we really need to present a more complex scene, then you have to consider the best use bitmaps to achieve.    Although Flash in the bitmap rendering efficiency is not the most superior (such as Flash and "brother" compared with Director), but rich visual content for only by Bitmap (bitmap with the complexity of the vector graphics rendering very low rate), this is based on many blocks in the game widely used as a Background pixel map of the reasons.    Incidentally to mention is that, although the Flash GIF, JPG and PNG are supported by, but the rendering speed or PNG has an absolute advantage, so we suggest that the flash in the best possible use of bitmaps PNG format. 

  Video clips (MovieClip) visibility [Below MovieClip will be referred to as mc] 

  You may often encountered such a situation: a large number not visible / mc waiting outside the screen out (for example, the game screen, maps, figures, etc.). 
  We should know that players have yet to spend some resources to deal with these visible / mc outside the screen, even if they are single-frame, non-state players. 

  One of the best solutions to these mc is a blank frame, when they are not on the screen, you can gotoAndStop () statement Jump to the frame, thereby reducing the player the demand for resources. 

  Be sure to remember that under such circumstances, the simple settings visibility attribute not visible (_visible = false) is null and void, players will continue to stay with these mc by the player or the complexity of the frame to the allocation of resources. 

  Array 

  Array data to be recorded in a variety of applications and games were widely used. 

  A typical example is based on block Flash games, in this type of game, the map is stored forming sometimes as arr [y] [x] the two-dimensional array.    While this is a very common method, but if one-dimensional array with the words, it can increase the efficiency of procedures.    Another important way to improve efficiency in the array array traversal for in the use of the time cycle for replacing the traditional grammar or while cycle. 
  For example: 

  A section of the code below 

   For (var i in arr) (if (arr [i]> 50) (/ /)) perform certain actions  

  It was significantly higher than that speed the implementation of this section of code: 

   For (var i = 0; i <10000; i) (if (arr [i]> 50) (/ /)) perform certain actions  

  The efficiency of the former than the latter was a 30% increase this figure in your game to Dizheng implementation of this section of code is even more valuable time! 

  Senior Optimization: 

  Here we are in the game for some commonly used code efficiency tests and the results are given.    Some of these ideas in this paper from the last mentioned some individuals or groups. 

  We have two different models of the computer was tested. 

  AthlonXP 2.6Ghz desktop 512 M memory, Windows2000Pro 

  P4 2.0Ghz notebooks, WindowsXP Home Edition 

  Each test is divided into three groups, are the final results from the average. 

  Test results in units of "milliseconds", reflecting the code execution time.    Obviously, the smaller the value, the better the performance of the code. 

  All code generated by the MX2004 compiler Flash6.0 version.    Interestingly, we can see from the MX and MX2004 compiler gap. 

  All details of the test can look at the PDF files (aw Note: no translation, very simple PDF files can be read) 

  I summarized the results of tests are out, share with you: 

  1) cycle for cycle and while 

  While recycling will be used for recycling better than efficiency.    However, the read data from the array, used for in-cycle the best choice! 

  Therefore, we do not recommend: 

   For (var i = 0; i <1000; i) (/ /) perform certain actions  

  The recommended 

   Var i = 1 while (i <1000) (/ /) perform certain actions  

  2) read data from the array 

  We passed the test found, for in the efficiency of the cycle of the cycle significantly higher than other methods.    See also: 

   Arr [] = MAX = 5000 / / Fill an array for (i = 0; i <MAX; i) (arr [i] = i) var item = null / / For Loop for (var i = 0; i <MAX ; i) (item = arr [i]) / / For In Loop for (var i in arr) (item = arr [i]) / / While Loop i = -1 while (i <MAX) (item = arr [ i])  

  3) write to the array data (while, for) 

  Cycle can be seen while slightly dominant. 

  4) _global (global) variables with the Timeline (Timeline) variables 

  We speculate using global variables can improve call variable speed, but the effect is not as obvious as expected. 

  5) single single, multi-line variable assignment 

  We found that single variable assignment efficiency much higher than many firms.    For example: 

   0 a = b = c = 0 = 0 d 100 e = 100  

  Efficiency is not as good as: 

   A = b = c = d = e = 100  

  6) variable name addressable 

  This test reflects the pre-addressable variable name is very important, especially in the cycle of time, we have to point to the small one.    This saves much time addressing. 

  For example: 

   Var num = null t = getTimer () for (var i = 0; i <MAX; i) (num = Math.floor (MAX) - Math.ceil (MAX)) t1.text = "Always lookup:" (getTimer () - t)  

  Is not as good as: 

   T = getTimer () var floor = = Math.floor var ceil Math.ceil for (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.    Take into account long variable name has its advantages (for example, ease of maintenance, etc.), it is suggested that the key parts (such as the large number of cycle time) to use short variable names, the best on the 1-2 characters. 

  8) cycle before and after the statement variables 

  Before the test, we think that cycle will be more variable statement before saving time Unexpectedly, the test results are not obvious, and even the contrary! 

   / / Internal getTimer statement t = () for (var i = 0; i <MAX; i) (i) var test1 = t1.text = "Inside:" (getTimer () - t) / / External statement t = getTimer () var test2 for (var i = 0; i <MAX; i) (i) = test2  

  9) if the use of nested structure 

  When used at the complex conditionals.    They break up into independent judgments nested structure is the best option.    The following code we have conducted tests and found that this effect significantly improved! 

   MAX = 20000 a = 1 b = 2 c = -3 d = 4 var i = MAX while (- i> -1) (if (a == 1 & 2 b & c == == == 3 & & d 4) (var k = d * a * b * c)) / / Below the judge more time-saving var i = MAX while (- i> -1) (if (a == 1) (if (b == 2) (if (c == 3) (if (d == 4) (var k = d * a * b * c)))))  

  11) TellTarget grammar with "points" compared Grammar 

  If you start from Flash5.0 contact Flash code, then you will recall that at that time, we have "tellTarget" to control the MC. 

  Here test show that the tellTarget more efficient than grammatical point.    Therefore, when necessary, we can consider such official has openly denied the Syntax (aw Note: personally think that a trance, do not understand why this is so. Test results but since the case, then there are also the feasibility……) 

   MAX = 10000 = mc _root.createEmptyMovieClip ( "test", 1000) function test_dot () (var i = MAX while (- i> -1) (mc._y mc._x = 10 = 10)) function test_tellTarget () (var i = MAX while (- i> -1) (tellTarget (mc) (_y _x = 10 = 10)))  

  12) Find local variables (the same way with this method of comparison) 

  Local methods for locating many variables.    We found that using this with more than advantages! 

   Obj = () = 1 obj.a obj.c obj.b = 2 = 3 = 4 obj.d obj.f obj.e = 5 = 6 = 7 obj.g obj.h = 8 obj.test1 useThis obj = . test2 = useWith MAX = 10000 function useThis () (var i = MAX while (- i> -1) (this.a = 2 = 1 this.b this.d this.c = 3 = 4 = this.e this.g this.f 5 = 6 = 7 = 8 this.h)) function useWith () (var i = MAX while (- i> -1) (with (this) (a = b = c = 2 3 d = e = 4 = 5 f 6 g = 7 = 8 h)))  

  13) Revolving monitor keyboard events 

  With the above-mentioned addressing the same, we have achieved to a point will have better efficiency, such as: 

   Key.isDown keyLeft keyDown = = Key.LEFT / / reuse if we (keyDown (keyLeft))  

  Attachment: We tested the code keys and keys found that the efficiency of constant is not much difference. 

  14) Math.floor () method with the int () 

  This issue has been in Flashkit forum had been raised.    Tests show that the old ways instead of int more efficient.    Our test results also reflect this point. 

  15) eval expression and grammar in brackets 

  We found no significant differences, and not as mentioned earlier, as the old expression than in brackets eval method and there is no significant advantage 

   Var mc = eval ( "_root.myMc" i) = var mc _root [ "myMc" i] / / efficiency of the two almost  

  16) involving MC cycle: Huan ASBroadcaster with the same cycle of difference 

  Test reflected by undisclosed ASBroadcaster methods can greatly increase the cycle of the MC operating efficiency.    Our tests, the establishment of the 500 MC, and then test them Clear by the time spent. 

  Traditional cycle: 

   SX MAX = 500 = 550 = 330 MovieClip.prototype.onCustomEvent SY = function () (this.removeMovieClip ()) function init () (var i = MAX var rnd = Math.random while (- i> -1) ( var m = _root.attachMovie (the "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]. onCustomEvent ()) res.text = "time:" (getTimer () - t))  

  The same effect with the incident Broadcasting (ASBroadcaster) 

   MAX = 500 = () evtManager ASBroadcaster.initialize (evtManager) SX = 550 = 330 MovieClip.prototype.onCustomEvent SY = function () (this.removeMovieClip ()) function init () (var i = MAX var rnd = Math.random while (- i> -1) (var m = _root.attachMovie (the "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))  

  MX04 with players for 6.0 compiler to generate documents: 

  In MX04 species, an interesting thing is that the script compiler performance improved a lot in all aspects.    The compiler in the new local, global variables are addressing efficiency greatly, and you can also, through the PDF file found many interesting results: addressing global variables variables faster than the time frame, and the nesting cycle has been improved .    Almost every one used MX04 compiled code efficiency is higher than the MX version. 

  Awflasher awflasher.com of: Why 6.0 compiler, it is still a considerable part of foreign customers in the use of MX6.0.    Although the 7.0 Player is free, but the software upgrade in the foreign country does not seem so fire, what immediately rose highest.    I guess some of it 

  Conclusion: 

  Results from these tests we found that the different needs, different code, we can greatly increase the efficiency of the implementation of the script.    Although we are here listed many of the optimized code, and that we need their own tests, there are many experiments (taking into account the different needs of each person) If you would like to more in-depth discussion of these issues.    We can come to the forum. 

  Aw of: 

  Translation finally finished, I myself learned a lot of good things, we can go and what issues gotoAndPlay official, can be made to my Blog! 

  This piece of html documents can be stored directly (browser - - Save time), does not contain any pictures, also went to the local Show:) 

Related articles:

JavaScript achieve unlimited menu-tree
  Download the code and presentation:    Click here to download the source files    Produced a very easy menu tree, you can add the lower-class unlimited menu, the menu is written through the table! NOTE: use of the head and body were added to the code corresponding regio...
FW text effects produced by example
  1, FW opened, a new documents, the size of self.    Rectangle drawing tools used in the editing area drawing a rectangular object, as a background, the background of cases as shown below    2, enter text in the editing area, font used a coarse fonts "Arial Black,&quo...
In the search engine at the top - "Bridge" page of the Road!
  (Editor's note: that is to say, "search engine" refers to the use of information search robot collection the real site search engine, such as YAHOO do not include this type of "Category." To further understanding of the concept of search engines and classification, Si...
Reith Miao FLASH2004 Series Guide (9) - lose weight to the source document
  Miao think the animation is exquisite in its humor, and widely circulated, now think Miao launched a series of tutorial, with his customary humor vivid animation on the entry FLASH knowledge, Flash empire authorized reprint of the initial version of this article 9 lesson: to the source docum...
JavaScript object-oriented support (6)
  ================================================== ====================    Qomolangma OpenProject v0.9    Category: Rich Web Client    Key words: JS OOP, JS Framwork, Rich Web Client, RIA, Web Component,    DOM, DTHML, CSS, JavaScript, JScript ...