jasu's blog
블로그 메뉴검색결과 리스트
AS3에 해당되는 글 126건
- 2007.06.15 [AS3] for each..in 문법
- 2007.06.15 [AS3] Object 형의 독립
- 2007.06.13 [AS3] Understanding garbage collection in Flash Player 9
- 2007.06.13 [AS3] ActionScript 3 Tip of the Day
- 2007.06.13 [AS3] ActionScript 3.0 첫 프로그래밍 1
- 2007.02.21 AS3 API 계층구조도 1
글
[AS3] for each..in 문법
for each (var num in myObj) {
trace (num);
}
//
출력 :
// 20
// 30
XML 또는 XMLList 오브젝트의 반복 처리를 실행.
var myXML:XML = <users>
<fname>Jane</fname>
<fname>Susan</fname>
<fname>John</fname>
</users>;
for each (var item in myXML.fname) {
trace(item);
}
/*
출력
Jane
Susan
John
*/
배열의 엘리먼트의 반복 처리를 실행할 수도 있음.
var myArray:Array = ["one", "two", "three"];
for each (var item in myArray) {
trace (item);
}
//
출력 :
// one
// two
// three
글
[AS3] Object 형의 독립
1. var obj:Object;
2. var obj;
하지만 ActionScript 3.0에서는 형을 지정되어 있지 않은 변수라고 하는 개념이 도입되었다. 이는 다음의 1, 2번과 같이 2 개의 방법으로 지정할 수 있다.
1. var obj:*;
2. var obj;
3. var obj:Object;
형이 지정되어 있지 않은 1번과 2번은 3번의 Object 형태의 변수와 같지는 않다. 주된 차이는 형이 지정되어 있지 않은 변수는 특별한 값 undefined 를 담을 수 있지만 Object 형태의 변수는 그 값을 보관 유지할 수 없다는 것이다. 오직 null값만이 존재할 수 있다. 이를 다시 말하면 ActionScript 3.0에서는 더 이상 형을 지정하지 않은 변수는 Object형이 아니라는 것이다. 이는ActionScript 2.0보다 형 변환에 따른 엄격한 규칙을 적용하고 있다고 할 수 있겠다.
글
[AS3] Understanding garbage collection in Flash Player 9
I've been playing around with ActionScript 3.0 for a while now, and I'm really excited by its capabilities. The raw execution speed by itself provides so many possibilities. Toss in E4X, sockets, byte arrays, the new display list model, RegEx methods, a formalized event and error model, and a few dozen other features for flavor, and you have a pretty heady brew.
With great power comes great responsibility, and this is very true for ActionScript 3.0. A side effect of all this new control is that the garbage collector is no longer able to make as many assumptions about what it should automatically tidy up for you. This means that Flash developers moving to ActionScript 3.0 will need to develop a very strong understanding of how the garbage collector operates, and how to work with it effectively. Building even seemingly simple games or applications without this knowledge could result in SWFs that leak like a sieve, hogging all of a system's resources (CPU/RAM) and causing the user's system to hang—potentially even forcing them to hard reboot their computer.
To understand how to optimize your code for ActionScript 3.0, you'll first need an understanding of how the garbage collector works in Flash Player 9. Flash has two processes for finding objects that are not in active use and removing them. This article looks at both techniques and describes how they are relevant to your code.
At the end of this article you can find a simulation of the garbage collector in Flash Player 9 that visually demonstrates the concepts explained herein.
About the garbage collector
The garbage collector is a behind-the-scenes process that is responsible for deallocating the memory used by objects that are no longer in use by the application. An inactive object is one that no longer has any references to it from other active objects. In order to understand this, it is very important to realize that when working with non-primitive types (anything other than Boolean, String, Number, uint, int), you are always passing around a reference to the object, not the object itself. When you delete a variable you remove the reference, not the object itself.
This is easily demonstrated in the code below:
// create a new object, and put a reference to it in a:
var a:Object = {foo:"bar"}
// copy the reference to the object into b:
var b:Object = a;
// delete the reference to the object in a:
delete(a);
// check to see that the object is still referenced by b:
trace(b.foo); // traces "bar", so the object still exists.
If I were to update the code in the example above and delete "b" as well, it would leave my object with no active references and free it for garbage collection. The ActionScript 3.0 garbage collector uses two methods for locating objects with no active references: reference counting and mark sweeping.
Reference counting
Reference counting is one of the simplest methods for keeping track of active objects, and has been used in Flash since ActionScript 1.0. When you create a reference to an object, its reference count is incremented. When you delete a reference, its reference count is decremented. If the reference count of an object reaches zero, it is marked for deletion by the garbage collector.
Here's an example:
var a:Object = {foo:"bar"}
// the object now has a reference count of 1 (a)
var b:Object = a;
// now it has a reference count of 2 (a & b)
delete(a);
// back to 1 (b)
delete(b);
// the reference count down is now 0
// the object can now be deallocated by the garbage collector
Reference counting is simple, it doesn't carry a huge CPU overhead, and it works well in most situations. Unfortunately, the reference counting method for garbage collection is not optimal when it comes to circular referencing. Circular referencing is the situation when objects cross-reference each other (directly, or indirectly via other objects). Even if the application is no longer actively using the objects, their reference counts remain above zero, so the garbage collector never removes them. The code below illustrates how this works:
var a:Object = {}
// create a second object, and reference the first object:
var b:Object = {foo:a};
// make the first object reference the second as well:
a.foo = b;
// delete both active application references:
delete(a);
delete(b);
In the code shown above, both of the active application references have been deleted. I no longer have any way of accessing the two objects from my application, but the reference counts of both objects are 1 because they reference each other. This situation can become much more complex (a references c, which references b, which references a, etc.) and can be difficult to deal with in code. Flash Player 6 and 7 had issues relating to circular referencing in XML objects: each XML node referenced both its children and its parent, so they were never deallocated. Fortunately, Flash Player 8 added a new garbage collection technique called mark and sweep.
Mark sweeping
The second strategy employed by the ActionScript 3.0 (and Flash Player 8) garbage collector to find inactive objects is a method called mark and sweep. Flash Player starts at the root object of your application (which is conveniently called the "root" in ActionScript 3.0) and walks through every reference in it, marking each object it finds.
Next, Flash Player iterates through each of the marked objects. It continues this behavior recursively until it has traversed the entire object tree of your application, marking everything it can reach through an active reference. At the end of this process, Flash Player can safely assume that any objects in memory that are not marked no longer have any active references to them and can be safely deallocated. Figure 1 illustrates how this works: The green references were followed by Flash Player during marking, the green objects are marked, and the white objects will be deallocated.
Mark and sweep is very accurate. However, because Flash Player has to traverse your entire object structure, the process is costly in terms of CPU usage. Flash Player 9 reduces this cost by carrying out iterative mark and sweep—the process occurs over a number of frames, instead of all at once—and by running this process only occasionally.
Deferred garbage collector and indeterminacy
In Flash Player 9, the garbage collector's operations are deferred. This is a very important thing to understand. Your objects will not be removed immediately when all active references are deleted. Rather, they will be removed at some indeterminate time in the future (from a developer standpoint). The garbage collector uses a set of heuristics that look at the RAM allocation and the size of the memory stack, among other things, to determine when to run. As a developer, you must accept the fact that you will have no way of knowing when, or even if, your inactive objects will get deallocated. You must also be aware that inactive objects will continue to execute indefinitely, until the garbage collector deallocates them, so your code will keep running (enterFrame events will continue), sounds will keep playing, loads will keep happening, other events will keep firing, and so on.
It's very important to remember that you have no control over when the garbage collector in Flash Player will deallocate your objects. As a developer, you will want to make the objects in your games and applications as inert as possible when you are finished with them. Strategies to manage this process will be the focus of my companion article, Resource management strategies in Flash Player 9.
Notice the sawtooth pattern of the total memory in the following garbage collection simulation (click Figure 2 or the link below it). The dips are caused when the collector carries out a sweep. Click on the chart to focus it, then press Spacebar to pause or restart, and hold the up/down arrows to change the memory usage trend as it runs.
As shown in the following simulation (click Figure 3 or the link below it), drag out objects (round rectangles) and references to those objects. Then run reference counts or mark and sweep to see which objects would be collected. The number in an object indicates the number of references to that object.
Where to go from here
Understanding garbage collection is going to be one of the most important steps for writing optimized code that ensures that your Flash project runs with minimal impact on the user's computer. Read my companion article, Resource management strategies in Flash Player 9, and visit the Flash Developer Center and Flash Player Developer Center.
Also check out my blog at gskinner.com to read more about weak references and download helper classes that I've written.
About the author
Grant Skinner is the CEO and chief architect of gskinner.com, a Flash development and consulting company. He works with leading new media agencies and progressive corporate clients to create cutting-edge applications, games, and multimedia pieces. His expertise in fusing coding with interface design, usability, marketing, and business logic has garnered him international acclaim and resulted in a number of prestigious industry awards, including Best Canadian Developer at FITC 2005. Grant maintains an active blog at gskinner.com/blog/ and an exhibit of his experimental work at incomplet.org.
국문 : http://www.adobe.com/kr/devnet/flashplayer/articles/garbage_collection.html
글
[AS3] ActionScript 3 Tip of the Day
The release of Flex Builder 2 is around the corner and though the next version of Flash is still a ways away, ActionScript 3 will be a big part of Flex 2 and the impending release of Flash Player 9 (which arrives with Flex). ActionScript 3 is the next step forward and to help with the transition (for those of you deciding to make it), I thought, since I've been working with AS3 a bit lately, I'd make a new Tip of the Day thread for ActionScript 3.0 to help people prepare. So here we go:
ActionScript 3 Tips and Tricks:
- 06-19-06: Change the frame rate of your movie
- 06-20-06: Class scope is now bound to class methods
- 06-21-06: Graphics Object and the Drawing API
- 06-22-06: New Variable Types
- 06-23-06: Display Objects
- 06-24-06: New Import Directive
- 06-25-06: Type Casting and the as Operator
- 06-26-06: Unique Class Variables
- 06-27-06: New MouseMove Behavior
- 06-28-06: The delete Keyword and Class Members
- 06-29-06: The Dictionary Class
- 06-30-06: Label Statements
- 07-01-06: Detecting When the Mouse Leaves the Movie
- 07-02-06: SimpleButton Instances
- 07-03-06: Commas in Shorthand Array Definitions
- 07-04-06: Package Block
- 07-05-06: Same-file Helper Classes
- 07-06-06: Access Attributes
- 07-07-06: Abstract Classes
- 07-08-06: The override Keyword
- 07-09-06: Using prototype
- 07-10-06: Regular Expression (RegExp) Support
- 07-11-06: Approach to Depth Sorting
- 07-12-06: Deep Object Copies with ByteArray
- 07-13-06: Similarly Named Instance and Static Properties
- 07-14-06: EventDispatcher
- 07-15-06: Events and Event Types
- 07-16-06: Writing Inline XML
- 07-17-06: Determine Instance Class or Superclass
- 07-18-06: super() Placement (Now Anywhere)
- 07-19-06: Determining Current Frame Label
- 07-20-06: Multiple Arguments in trace()
- 07-21-06: Calling Event Handlers without Events
- 07-22-06: URLRequest for URL Strings
- 07-23-06: XML vs. XMLDocument
- 07-24-06: Loading Text and XML with URLLoader
- 07-25-06: is Operator (vs instanceof)
- 07-26-06: Flash 9: Timelines as Classes
- 07-27-06: RegExp: Email Validation
- 07-28-06: Render Event
- 07-29-06: XML: @ Operator for Attributes
- 07-30-06: Event Propagation Support
- 07-31-06: Get Sound Spectrum Information
- 08-01-06: Number() Conversion No Longer Interprets Octals
- 08-02-06: Garbage Collection: Reference Counting & Mark and Sweep
- 08-03-06: Weak References
- 08-04-06: Flash 9: BitmapData and Bitmaps from the Library
- 08-05-06: Changes in typeof
- 08-06-06: getBounds() vs getRect()
- 08-07-06: for..in and for each..in
- 08-08-06: Default Values for Function Parameters
- 08-09-06: Undetermined Number of Arguments With ...(rest)
- 08-10-06: arguments
- 08-11-06: Support for Namespaces
- 08-12-06: Namespaces: Name Qualifier Operator (::)
- 08-13-06: dynamic is Not Inherited
- 08-14-06: Creating a mouseWithin Event
- 08-15-06: Prevent Overriding and Subclassing with final
- 08-16-06: MXMLC: SWF Metadata Tag
- 08-17-06: Proxy Class
- 08-18-06: in Operator
- 08-19-06: Proxy: getProperty and setProperty
- 08-20-06: Flash 9: Display Object Variables and Instance Names
- 08-21-06: XML: XML and XMLList
- 08-22-06: Constants
- 08-23-06: duplicateMovieClip Replacement
- 08-24-06: Proxy: callProperty
- 08-25-06: Creating graphics Copies
- 08-26-06: TextField.appendText()
- 08-27-06: include Directive
- 08-28-06: Duplicate Variable Definitions
- 08-29-06: mouseEnabled and Event Blocking
- 08-30-06: mouseChildren with Event Propagation
- 08-31-06: rollOver and rollOut vs. mouseOver and mouseOut
- 09-01-06: DisplayObjectContainer contains()
- 09-02-06: Cleaning Up Event Listeners
- 09-03-06: Detecting Addition to or Removal from Stage
- 09-04-06: Event Phases and Event Capturing
- 09-05-06: Determining Event Phase
- 09-06-06: Preventing Event Propagation
- 09-07-06: Global Events
- 09-08-06: Detecting a mouseUp Outside
- 09-09-06: Flash 9: Document Class
- 09-10-06: Access to stage and root
- 09-11-06: Namespaces: use namespace Directive
- 09-12-06: No More Color Class; Use ColorTransform
- 09-13-06: Runtime Errors; Error Class
- 09-14-06: Errors: try..catch..finally and Exception Handling
- 09-15-06: Errors: Asynchronous Exception Handling
- 09-16-06: XML: Children (.) and Decendants (..)
- 09-17-06: Array.indexOf (Array.lastIndexOf())
- 09-18-06: asfunction: Now event:
- 09-19-06: Proxy: Property Enumeration (nextName(), nextValue(), and nextNameIndex())
- 09-20-06: Event Capturing and mouseEnabled
- 09-21-06: Flash 9: Strict Mode
- 09-22-06: System.totalMemory
- 09-23-06: Closing Net Connections
- 09-24-06: Timer Class
- 09-25-06: AVM2 (AS3) to AVM1 (AS2/AS1) Communication via LocalConnection
- 09-26-06: ByteArray Class
100 AS3 tips! After tip 100, no longer will they be added daily
글
[AS3] ActionScript 3.0 첫 프로그래밍
간단한 코딩이지만 직접 접하고 보니 이제야 비로소 정리가 되는 듯 하다. 기존에 호환성 문제로 인해서 불필요하게 사용되었던 군더더기가 많이 빠지고 깔끔해 졌다는 느낌이다. 형식적이고 자율적인 구조로 인해서 혼돈이 왔던 부분들은 간결한 형태로 변화되었고 그 형태 또한 만족스럽다.
하지만 그 동안 편리하게 사용되었던 기능들도 그러한 진화를 바탕으로 다소 불편한 부분도 없지 않다. 그러나 그 불편함 또한 개발자에게 동기와 목적을 확실하게 이미지화 하기 때문에 납득할 만한 변화라는 생각이다.
앞으로 플래시를 사용하는 모든 분야의 발 빠른 변화가 상당히 재미있어질 것 같다…
// Rec.as