节省内存
对于应用程序(尤其桌面应用程序)开发一直非常重要。然而,内存的使用量对移动设备来说非常重要,因此有必要限制应用程序占用的内存量。显示对象选择适当的显示对象。
ActionScript 3.0 包含很多显示对象。要限制内存用量,最简单的优化技巧之一是使用合适类型的显示对象。对于非交互式简单形状,请使用 Shape 对象。对于不需要时间轴的交互式对象,请使用 Sprite 对象。对于使用时间轴的动画,请使用MovieClip 对象。应始终为应用程序选择最有效的对象类型。
以下代码显示不同显示对象的内存使用量:
trace(getSize(new Shape()));
// output: 236
trace(getSize(new Sprite()));
// output: 412
trace(getSize(new MovieClip()));
// output: 440
getSize() 方法显示对象在内存中占用的字节数。可以看到,如果不需要 MovieClip 对象的功能,使用多个 MovieClip 对象(而不是使用简单的 Shape 对象)会浪费内存。
原始类型
使用 getSize() 方法为代码设置基准并确定任务的最有效对象。所有原始类型(String 除外)在内存中都是占用 4 – 8 个字节。使用特定类型的基元无法优化内存:
// Primitive types
var a:Number;
trace(getSize(a));
// output: 8
var b:int;
trace(getSize(b));
// output: 4
var c:uint;
trace(getSize(c));
// output: 4
var d:Boolean;
trace(getSize(d));
// output: 4
var e:String;
trace(getSize(e));
// output: 4
如果没有为表示 64 位值的数字分配值, ActionScript 虚拟机 (AVM) 将为其分配 8 个字节。所有其他原始类型存储时均占用
4 个字节。
// Primitive types
var a:Number = 8;
trace(getSize(a));
// output: 4
a = Number.MAX_VALUE;
trace(getSize(a));
// output: 8
此行为不同于 String 类型。分配的存储量基于 String 的长度:
var name:String;
trace(getSize(name));
// output: 4
name = "";
trace(getSize(name));
// output: 24
name = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the
industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into
electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release
of Letraset sheets containing Lorem Ipsum passages, and more recently w