Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 get current time without creating new object

How can I get the current number of milliseconds since midnight January 1, 1970 in AS3 without having to use the 'new' operator? I'm asking because I need to do this about 100 times per second and currently try to reduce heap allocations to keep gc low.

like image 372
matthias_buehlmann Avatar asked Feb 16 '23 05:02

matthias_buehlmann


2 Answers

You should create it once and then add milliseconds, that passed since that creation with getTimer(); You will also need a helping variable to store your Data creation time;

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
        }
    }
}

If you need just to know what time has passed since last frame, without knowing the day of the week, or a year, you can just use getTimer(); on it's own, it's more efficient

like image 175
KumoKairo Avatar answered Apr 02 '23 05:04

KumoKairo


Util method that I use:

// 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);
}
like image 22
fsbmain Avatar answered Apr 02 '23 03:04

fsbmain