代码改变世界

AS3优化性能笔记一

2013-02-17 10:48  游乐场123  阅读(179)  评论(0编辑  收藏  举报

尽可能使用Vector类而不是Array类,尤其是固定长度的Vector类。

Array类

var coordinates:Array = new Array();
 
var started:Number = getTimer();
 
for (var i:int = 0; i<t; 300000; i++)
 
{
 
coordinates[i] = Math.random()*1024;
 
}
 
trace(getTimer() - started);
 
// output: 107

Vector类

var coordinates:Vector.<Number> = new Vector.<Number>();
var started:Number = getTimer();
for (var i:int = 0; i< 300000; i++)
{
coordinates[i] = Math.random()*1024;
}
trace(getTimer() - started);
// output: 72

固定长度的Vector类

var coordinates:Vector.<Number> = new Vector.<Number>(300000, true);
var started:Number = getTimer();
for (var i:int = 0; i< 300000; i++)
{
coordinates[i] = Math.random()*1024;
}
trace(getTimer() - started);
// output: 48

事件捕获和冒泡

使用事件捕获和冒泡可以最大程度地减少事件处理函数。最好在一个对象(而不是多个对象)注册时间处理函数以提高性能,例如在具有多个child的parent上注册事件处理函数而不是为每一个child注册事件处理函数。

例如删除屏幕上被击中的苹果游戏中,以下是为每一个苹果调度MouseEvent.CLICK事件。此代码对各个Apple实例调用addEventListener()方法。此外,还会在用户单击每个苹果时使用removeEventListener()方法删除对应的侦听器。

const MAX_NUM:int = 10;
var sceneWidth:int = stage.stageWidth;
var sceneHeight:int = stage.stageHeight;
var currentApple:InteractiveObject;
var currentAppleClicked:InteractiveObject;
 
for ( var i:int = 0; i< MAX_NUM; i++ )
{
currentApple = new Apple();
currentApple.x = Math.random()*sceneWidth;
currentApple.y = Math.random()*sceneHeight;
addChild ( currentApple );
currentApple.addEventListener ( MouseEvent.CLICK, onAppleClick);
}
 
function onAppleClick ( e:MouseEvent ):void
{
currentAppleClicked = e.currentTarget as InteractiveObject;
currentAppleClicked.removeEventListener(MouseEvent.CLICK, onAppleClick );
removeChild ( currentAppleClicked );
}

使用捕获阶段侦听来自父对象的事件。

const MAX_NUM:int = 10;
var sceneWidth:int = stage.stageWidth;
var sceneHeight:int = stage.stageHeight;
var currentApple:InteractiveObject;
var currentAppleClicked:InteractiveObject;
var container:Sprite = new Sprite();
addChild ( container );
 
// 第三个参数useCapture设置为true,该侦听器只在捕获阶段进行侦听
container.addEventListener ( MouseEvent.CLICK, onAppleClick, true );
 
for ( var i:int = 0; i< MAX_NUM; i++ )
{
currentApple = new Apple();
currentApple.x = Math.random()*sceneWidth;
currentApple.y = Math.random()*sceneHeight;
container.addChild ( currentApple );
}
 
function onAppleClick ( e:MouseEvent ):void
{
currentAppleClicked = e.target as InteractiveObject;
container.removeChild ( currentAppleClicked );
}

可通过停止事件传播(此操作将阻止继续传播事件)来进一步优化处理函数。

function onAppleClick ( e:MouseEvent ):void
{
e.stopPropagation();
currentAppleClicked = e.target as InteractiveObject;
container.removeChild ( currentAppleClicked );
}

冒泡阶段也可用于捕捉事件,方法是将false作为第三个参数传递到addEventListener()方法。因为默认值为false,因此可以忽略。