AS3获取当前时间而不创建新对象

时间:2013-09-21 00:30:37

标签: actionscript-3

如何在AS3中获取1970年1月1日午夜以来的当前毫秒数,而无需使用“新”运算符?我问,因为我需要每秒执行大约100次,并且当前尝试减少堆分配以保持gc低。

2 个答案:

答案 0 :(得分:4)

我使用的方法:

// Get time since the epoch and time since the VM was started
private static const dateTime:Number = new Date().time;
private static const dateTimestamp:uint = getTimer();
/**
 * Current time in ms
 */ 
public static function getCurrentTime():Number
{
    return dateTime + (getTimer() - dateTimestamp);
}

答案 1 :(得分:3)

你应该创建一次然后添加毫秒,这是自创建以来用getTimer()传递的;您还需要一个帮助变量来存储您的数据创建时间;

package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.utils.getTimer;

    public class Main extends Sprite 
    {
        private var _myLittleDate:Date;
        private var _myLittleDateCreationTime:Number;

        public function Main():void 
        {
            _myLittleDate = new Date(); //Our first and only object creation
            _myLittleDateCreationTime = getTimer(); //Store it's creation time
            addEventListener(Event.ENTER_FRAME, onEnterFrame); //Check function
        }

        private function onEnterFrame(e:Event):void 
        {
            _myLittleDate.time += ( getTimer() - _myLittleDateCreationTime );
            trace(_myLittleDate); //You get valid, refreshed data object here
            _myLittleDateCreationTime = getTimer(); // Don't forget to update your initial time
            //It's accurate since method .getTimer() is accurate itself
            //You can even compare two Data object by creating another and tracing it right here
        }
    }
}

如果您只需要知道自上一帧以来已经过了多少时间,而不知道一周中的某一天或一年,您可以使用getTimer();在它自己,它更有效