目前,我正在尝试一个非常简单的 GUI 绘图......“引擎”(我想你可以这么称呼它)。它的要点:
- 有一个 FrontController 被用户请求击中;每个请求都有一个uid
- 每个uid(读作“页面”)都有其上存在的组件(“模块”)的声明
- 组件是Sprite的子类,本质上是唯一的
自然,我需要一种隐藏/显示这些精灵的方法。目前,我拥有它就像 Flex 默认拥有它一样 - 方式是“如果我们在一个 comp 可见的地方,创建它,缓存它并在每次它再次可见时重用它”。
问题是——这将是更合适和更有效的隐藏和显示方式——通过addChild
/removeChild
或切换visible
。
我的看法是:
visible
又快又脏(在第一次测试中)visible
不会创建一连串冒泡事件,例如Event.ADDED
或Event.REMOVED
- 不可见的组件不会获得鼠标事件
当我removeChild
确定组件将不再需要在屏幕上时(或者缓存太大,例如),我会调用它
stackoverflow'ers / AS3-crazy 的人是怎么想的?
更新:这是一本很好的读物(忘记了谷歌)。
我会坚持visible
; 它似乎更适合我的任务;Adobe 的手册“优化 FLASH 平台的性能”,第 15 页。69给了我更多的信心。
这是我为感兴趣的人测试的代码片段:
package
{
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.getTimer;
/**
* Simple benchmark to test alternatives for hiding and showing
* DisplayObject.
*
* Use:
* <code>
* new DisplayBM(stage);
* </code>
*
* Hit:
* - "1" to addChild (note that hitting it 2 times is expensive; i think
* this is because the player has to check whether or not the comp is
* used elsewhere)
* - "q" to removeChild (2 times in a row will throw an exception)
* - "2" to set visible to true
* - "w" to set visible to false
*
* @author Vasi Grigorash
*/
public class DisplayBM{
public function DisplayBM(stage:Stage){
super();
var insts:uint = 5000;
var v:Vector.<Sprite> = new Vector.<Sprite>(insts);
var i:Number = v.length, s:Sprite
while (i--){
s = new Sprite;
s.graphics.beginFill(Math.random() * 0xFFFFFF);
s.graphics.drawRect(
Math.random() * stage.stageWidth,
Math.random() * stage.stageHeight,
10,
10
);
s.graphics.endFill();
v[i] = s;
}
var store:Object = {};
store[Event.ADDED] = null;
store[Event.REMOVED] = null;
var count:Function = function(e:Event):void{
store[e.type]++;
}
var keydown:Function = function (e:KeyboardEvent):void{
var key:String
//clear event counts from last run
for (key in store){
store[key] = 0;
}
stage.addEventListener(Event.ADDED, count);
stage.addEventListener(Event.REMOVED, count);
var s0:uint = getTimer(), op:String;
var i:Number = v.length;
if (e.keyCode === Keyboard.NUMBER_1){
op = 'addChild';
while (i--){
stage.addChild(v[i]);
}
}
if (e.keyCode === Keyboard.Q){
op = 'removeChild';
while (i--){
stage.removeChild(v[i]);
}
}
if (e.keyCode === Keyboard.NUMBER_2){
op = 'visibile';
while (i--){
v[i].visible = true;
}
}
if (e.keyCode === Keyboard.W){
op = 'invisibile';
while (i--){
v[i].visible = false;
}
}
if (op){
//format events
var events:Array = [];
for (key in store){
events.push(key + ' : ' + store[key])
}
trace(op + ' took ' + (getTimer() - s0) + ' ' + events.join(','));
}
stage.removeEventListener(Event.ADDED, count);
stage.removeEventListener(Event.REMOVED, count);
}
//autodispatch
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
}
}
}