AS3深拷贝数据对象(2)深拷贝VO对象

时间:2022-10-02 19:55:48

Topic:对于用户自定义的VO对象进行深拷贝,一种VO对象的某属性可能是另一种VO对象的实例。

方法1:通过传说中的“AS3隐藏特性——ByteArray.writeObject和readObject”进行操作,代码如下:

registerClassAlias("test.vo.ResVO", ResVO);
registerClassAlias("test.vo.TestVO", TestVO);
var vo:TestVO = new TestVO();
vo.name = "abc";
vo.level = 20;
vo.res = new ResVO();
vo.res.gold = 500;
var nT:int = getTimer();
var voClone:TestVO;
for (var i:int = 0; i < 100000; i++) 
{
    voClone = vo.clone();
}
trace(getTimer() - nT);

TestVO类代码如下:

public class TestVO
{
    private var m_strName:String;
    private var m_nLv:int;
    private var m_obRes:ResVO;
    /**
     */
    public function get level():int{return m_nLv};
public function set level(nLv:int):void { m_nLv = nLv; } public function get name():String{return m_strName};
public function set name(strName:String):void { m_strName = strName; } public function get res():ResVO{return m_obRes};
public function set res(value:ResVO):void { m_obRes = value; } /** */ public function clone():TestVO { var bta:ByteArray = new ByteArray(); bta.writeObject(this); bta.position = 0; return bta.readObject(); } }

ResVO类代码如下:

public class ResVO
{
    private var m_nGold:int;
    /**
     */
    public function get gold():int{return m_nGold};
public function set gold(value:int):void { m_nGold = value; } }

执行时间:average(1662,1669,1681,1695,1691)=1680ms

另外,我们可以对TestVO.clone()函数稍加修改,使其中的ByteArray可以重用,代码如下:

public function clone(bta:ByteArray):TestVO
{
    bta.length = 0;
    bta.writeObject(this);
    bta.position = 0;
    return bta.readObject();
}

执行时间:average(1582,1581,1583,1575,1590)=1582ms


方法2:在VO类的clone方法中对属性逐个赋值

TestVO.clone()函数代码如下:

public function clone():TestVO
{
    var voClone:TestVO = new TestVO();
    voClone.level = m_nLv;
    voClone.name = m_strName;
    voClone.res = m_obRes.clone();
    return voClone;
}

(此处省略ResVO.clone()函数代码)

执行时间:average(187,187,194,186,188)=188ms