34 Replies Latest reply on Jul 10, 2009 5:00 AM by meshgraphics

    Reusing a Date object.

    Lopo Nopo

      Hi!

       

      I want to know if it's possible to re-use a Date object instead of declaring a 'new' one each time.

      My application is going to declare a LOT of these, if I'll have to...

       

      Besides, isn't it a good idea to let ActionScript have a 'delete' keyword?

       

      Thank you all.

        • 1. Re: Reusing a Date object.
          Gregory Lafrance Level 6

          You should just be able to reset the date for the Date object, thus reusing it.

          • 2. Re: Reusing a Date object.
            Lopo Nopo Level 1

            Sorry for a dumb question but how do I actually reset it?

            I see no function which hint for that..

            A function name would do the job...

             

            Thanks for responding.

            • 3. Re: Reusing a Date object.
              meshgraphics Level 2

              You can make 100 date objects per second pretty reliably.  Something like this works well

               

              frameRate=100

               

              function myEnterFrame(e:event){

              curTime = new Date();

              myTextArea.text += String(curTime +"\n");

              }

              • 4. Re: Reusing a Date object.
                rtalton Level 4

                re-use a previously used date object like this:

                myOldDateObject = new Date();

                • 5. Re: Reusing a Date object.
                  GordonSmith Level 4

                  That doesn't re-use the Date instance. It creates a new one and makes the var point to the new instance rather than the old instance. To reuse a Date instance, simply set properties like 'year', 'month', etc.

                   

                  Gordon Smith

                  Adobe Flex SDK Team

                  • 6. Re: Reusing a Date object.
                    rtalton Level 4

                    news to me....

                    So, assigning a new Date to an existing var creates a new date object, eh?

                    Where can one see the "old" date objects that once were assigned to the var? Since they aren't assigned to a var anymore, are they just floating around in memory somewhere?

                    • 7. Re: Reusing a Date object.
                      GordonSmith Level 4

                      The 'new' operator always makes a new instance.

                       

                      myOldDateObject does not keep track of what instances it used to refer to, just like when you have var n:int and set n = 1 and then n = 2, n doesn't remember that it used to be 1.

                       

                      When there are no references to an instance, it becomes eligible for garbage collection so that it doesn't continue taking up memory. However, when the garbage collector decides to run, and which eligible objects actually get collected, is up to the Flash Player.

                       

                      Gordon Smith

                      Adobe Flex SDK Team

                      • 8. Re: Reusing a Date object.
                        Lopo Nopo Level 1

                        Gordon,


                        Setting properties like 'year', 'month' etc' is obvious.

                        What I mean is get the current time.

                         

                        Example:

                         

                        var nNow:Number = 0;

                        var dateObject:Date = new Date();

                        nNow = dateObject.getTime(); // say it returns 100000

                        // do some other stuff here

                        nNow = dateObject.getTime(); // now after 1000ms, it returns 101000

                         

                        Now I'm sure it's clear.

                        Any suggestions?

                         

                        Thanks!

                        • 9. Re: Reusing a Date object.
                          meshgraphics Level 2

                          I think you're getting mixed up with removing an object from the display list.

                           

                          Reassigning an int variable is not the same as removing a reference.

                          • 10. Re: Reusing a Date object.
                            meshgraphics Level 2

                            var nNow:Number = 0;

                            var dateObject:Date = new Date();

                            nNow = dateObject.getTime(); // say it returns 100000

                            // do some other stuff here

                            nNow = dateObject.getTime(); // now after 1000ms, it returns 101000

                             

                             

                            That doesn't look like it works to me.  A method works on the data that is in the object.  Like getDay() will give you the day of what is in the DAte obj.

                            • 11. Re: Reusing a Date object.
                              GordonSmith Level 4

                              The only way I know of to get the current system time is to make a new Date instance.

                               

                              Gordon Smith

                              Adobe Flex SDK Team

                              • 12. Re: Reusing a Date object.
                                GordonSmith Level 4

                                To meshgraphics - Which of my statements do you disagree with?

                                 

                                Gordon Smith

                                Adobe Flex SDK Team

                                • 13. Re: Reusing a Date object.
                                  meshgraphics Level 2

                                  Like my example above, I've been hitting the new Date() constructor pretty hard.  I didn't see a lot of memory usage.  Maybe they are getting garbage collected?  I assumed the same space was being overwritten.

                                   

                                  I'll get back to ya on that.

                                  • 14. Re: Reusing a Date object.
                                    rtalton Level 4

                                    @Lopo: You lost me!

                                    @Gordon: I wasn't being technically accurate, but using new Date() will repopulate the var with the latest date/time, which is what I thought Lopo wanted. Your comment re: Date Objects is a little misleading, although technically accurate. No one wants to think that re-populating a var is going to leave old objects laying around in memory, hence my comments. Otherwise, we'd be creating new vars all the time, and destroying the old ones. Inefficient and of course, AS3 doesn't require this.

                                    • 15. Re: Reusing a Date object.
                                      GordonSmith Level 4

                                      @meshgraphics: Date instances are probably only a few dozen bytes each, and since you are only maintaining a reference to the most recently created one, all the earlier ones are eligible for garbage collection. As for whether the space of a previous Date instance gets reused for a new Date instance, I don't think the Player's memory manager works this way.

                                      • 16. Re: Reusing a Date object.
                                        GordonSmith Level 4

                                        @rtalton: You seem to have a conceptual confusion between instances -- which are created by the 'new' operator at runtime -- and vars that contain references to instances -- which are declared by 'var' statements at compile time. You can create new instances at runtime, but you cannot create new vars at runtime. Vars are either inside objects, or inside classes, or inside the stack frames of currently executing functions. In each of these three cases, the vars that exist are determined at compile time by your 'var' declarations. Since there is in general a many-to-one relationship (many different vars can all refer to the same instance) it's important not to confuse the two.

                                         

                                        Sorry if I'm being pedantic... I can't tell whether you're just being a bit loose with terminology or have a actual misunderstanding of how AS works.

                                         

                                        Gordon Smith

                                        Adobe Flex SDK Team

                                        • 17. Re: Reusing a Date object.
                                          meshgraphics Level 2

                                           

                                          OK. If we're getting in to the finer points of this thing:

                                           

                                          What is garbage collection and when does it happen?

                                           

                                          Is garbage collection going to happen inside a loop with a recursive call to an instantiator ?

                                           

                                           

                                          do {

                                               curTime = new Date();

                                          } (while curTime < maxTime)

                                           

                                           

                                           

                                          I saw a note on garbage collection: It does not happen when the prog is idle? How idle is idle?

                                           

                                           

                                          • 18. Re: Reusing a Date object.
                                            rtalton Level 4

                                            @Gordon: Yes, you are being pedantic, but your apology is accepted.

                                            My choice of language is meant to help Lopo, not raise the hackles of Adobe employees or others who take umbrage at any perception of straying from the path of AS terminology accuracy.

                                             

                                            Remember that most users of Flex, like myself, are not computer scientists, and it helps to see real-world, practical examples and help from fellow Flex developers. I see allegedly inaccurate statements made in this forum all the time, but the advice being articulated is sound and practical nonetheless.

                                             

                                            Being an expert in any field does not make one a teacher. Reading anything in the Flex help documentation will confirm that statement. I sometimes need to comb the interweb all day looking for solutions to Flex issues. I buy books, read blogs, go to Flex User Group meetings--AND I lurk in this forum. I read and interpret the writings of people from many different countries, cultures and backgrounds, with or without a good grasp of the English language. Many are very frustrated with the lack of simple answers to their problems. Kudos to Adobe for creating this forum to address this deficiency in their documentation.

                                             

                                            The bottom line is: Adobe's documentation is imperfect and that's why this forum exists. I, too, am imperfect. But I'm not going to let that stop me from providing assistance to someone working through an issue I had to work through at one time. People have helped me, and I'm just giving back. I do it the best way I can. Just like you. Feel the love! Group hug and let's get back to work.

                                            • 19. Re: Reusing a Date object.
                                              Lopo Nopo Level 1

                                              Ok, I see. Thank you all.

                                               

                                              Just to make it more clear, and maybe the Flex developers will actually consider it, I meant to the following C++ code:

                                               

                                              void main()
                                              {
                                                  unsigned int nTime = 0;
                                                  nTime = GetTickCount();
                                                  Sleep(1000); // sleeping for 1sec
                                                  nTime = GetTickCount();
                                              }

                                               

                                              See? Very simple - no object was created whatsoever - I'm sure you can provide a nice static function for that.

                                              I think this basic thing should be available, it's a fundamental thing.

                                               

                                              Consider this thread as a request for the next Flex/ActionScript 'reincarnation'

                                              • 20. Re: Reusing a Date object.
                                                GordonSmith Level 4

                                                > What is garbage collection and when does it happen?

                                                 

                                                Garbage collection is the freeing of memory taked up by instances that aren't in use any more. An instance is in use only if other objects (or classes, or function stack frames) contain a reference to it. The garbage collector is also smart enough that if A contains a reference to B and B contains a reference to A, but nobody else refers to either A or B, then they're garbage.

                                                 

                                                As for when it happens, the best I can offer is that the Flash Player does garbage collection whenever it feels like it. The actual algorithm is apparently complex enough that I've never succeeded in getting a simple explanation of it from the Player team. It evolves from release to release as well, so there are no guarantees about its details.

                                                 

                                                > Is garbage collection going to happen inside a loop with a recursive call to an instantiator?

                                                 

                                                I'm not sure, but I would expect it to. If enough unused instances build up and take up too much memory in the Player's opinion, it should garbage-collect them, even if you are inside a loop.

                                                 

                                                BTW, at the risk of more pedantry, there is no recursive call in the loop you showed. Recursion is when a method calls itself. A do-loop is just a form of iteration, not recursion.

                                                 

                                                > I saw a note on garbage collection: It does not happen when the prog is idle? How idle is idle?

                                                 

                                                I haven't read this. I'm not sure whether it's accurate and I don't know what the criteria for idleness are. And if it IS true in Player 10, it might not be true in Player 11.

                                                 

                                                In the Flash Player, as in other virtual machines, garbage collection is transparent... it just happens behind the scenes without you knowing about it. The main thing that AS developers need to worry about it making sure that there are no references to instances that you want to be GC'd. This can sometimes be quite tricky. For example, any object which dispatches events has references to all of its listeners.

                                                 

                                                Gordon Smith

                                                Adobe Flex SDK Team

                                                • 21. Re: Reusing a Date object.
                                                  GordonSmith Level 4

                                                  @Lopo The Player team has given a great deal of thought to whether multiple threads should be supported in ActionScript. They believe the answer is No, because of the complications that multithreading creates. ActionScript is likely to remain a single-threaded programming environment for simplicity.

                                                   

                                                  Gordon Smith

                                                  Adobe Flex SDK Team

                                                  • 22. Re: Reusing a Date object.
                                                    GordonSmith Level 4

                                                    @Lopo Maybe you could use a single Timer instance and call getTimer() in a handler for the 'timer' event that it dispatches.

                                                     

                                                    Gordon Smith

                                                    Adobe Flex SDK Team

                                                    • 23. Re: Reusing a Date object.
                                                      meshgraphics Level 2

                                                      fyi,

                                                      Here's what I'm getting on full open timer.

                                                       

                                                       

                                                       

                                                      internal var fullOpenTimer:Timer = new

                                                      Timer(0);

                                                       

                                                       

                                                       

                                                       

                                                       

                                                       

                                                       

                                                      internal function

                                                      fastTimer(e:TimerEvent){

                                                      trace

                                                       

                                                       

                                                      (String(new

                                                      Date().time ));

                                                       

                                                      //OUtput

                                                      1247005496355

                                                      1247005496371

                                                      1247005496371

                                                      1247005496371

                                                      1247005496387

                                                      1247005496387

                                                      1247005496387

                                                      1247005496402

                                                      1247005496402

                                                      1247005496402

                                                      1247005496418

                                                      1247005496418

                                                      1247005496418

                                                      1247005496418

                                                      1247005496434

                                                      1247005496434

                                                      1247005496434

                                                      1247005496449

                                                      • 24. Re: Reusing a Date object.
                                                        GordonSmith Level 4

                                                        It looks like the system clock is accurate to only 16 ms (1/60 of a second).

                                                         

                                                        Gordon Smith

                                                        Adobe Flex SDK Team

                                                        • 25. Re: Reusing a Date object.
                                                          Ansury Level 3

                                                          rtalton wrote:

                                                           

                                                          @Gordon: Yes, you are being pedantic, but your apology is accepted.

                                                          My choice of language is meant to help Lopo, not raise the hackles of Adobe employees or others who take umbrage at any perception of straying from the path of AS terminology accuracy.

                                                           

                                                           

                                                          Not just to resurrect a dead horse but rtalton, in Gordon's defense, I had the urge to make a correction too.    This is extremely confusing for someone new to object oriented terminology and you shouldn't use the terminology like this:

                                                          rtalton wrote:

                                                           

                                                          re-use a previously used date object like this:

                                                          myOldDateObject = new Date();

                                                          Unless you used the wrong word and meant to type "reference", that's just going to offend every OO developer who sees it.

                                                          • 26. Re: Reusing a Date object.
                                                            Ansury Level 3

                                                            Lopo Nopo wrote:

                                                             

                                                             

                                                            Besides, isn't it a good idea to let ActionScript have a 'delete' keyword?

                                                             

                                                            Thank you all.

                                                             

                                                            Either I was too lazy and skipped a (long) post answering this question, or it was never answered. Short answer is that (while I admit I did think memory management in C++ with delete and pointers and such was fun), AS (like Java) automagically garbage collects objects no longer referenced, so it's just not needed.

                                                             

                                                            My "other" answer is that yes, AS should have "delete"!  And pointers!    But only because I miss C and C++, those were fun times...

                                                            • 27. Re: Reusing a Date object.
                                                              GordonSmith Level 4

                                                              I've programmed in both C++ and ActionScript and now prefer AS, primarily because it's garbage-collected. There are far fewer memory-related bugs in software written with garbage-collected software. You are no more likely to have memory leaks, and you never have to worry about dangling pointers, etc.

                                                               

                                                              BTW, ActionScript DOES have a 'delete' operator, but it isn't the opposite of 'new'. Instead it's used to delete properties created at runtime inside instances of dynamic classes:

                                                               

                                                              var o:Object = {};

                                                              trace("foo" in o, o.foo); // false undefined

                                                              o.foo = 1;

                                                              trace("foo" in o, o.foo); // true 1

                                                              delete o.foo;

                                                              trace("foo" in o, o.foo); // false undefined

                                                               

                                                              Gordon Smith

                                                              Adobe Flex SDK Team

                                                              • 28. Re: Reusing a Date object.
                                                                Ansury Level 3

                                                                Oh yeah!  I've seen that before in docs, but never used it!  (It's too scary and I can't think of a reason.)  Well bleh, how am I going to illogically advocate a return to the C++ days now when you guys already hogged the keyword for something else? 

                                                                • 30. Re: Reusing a Date object.
                                                                  rtalton Level 4

                                                                  @Ansury: I'm sure some folks desire/crave your validation. I don't, and I'm fairly certain Gordon doesn't either. Gordon made his point to me in a professional manner; your comments are unnecessary and were not required nor requested. In other words, Ansury, you have contributed nothing to this thread. My answer to a person seeking help stands. Bottom line is, it works, and no one has offered any better alternative.

                                                                   

                                                                  After reviewing your comments, my response to you would be:

                                                                  • Do an assessment.
                                                                  • Offer help.
                                                                  • Prepare a sample.
                                                                  • Energize the seeker.

                                                                   

                                                                  Instead of parsing my words, parse Lopo's and try to help her/him.

                                                                   

                                                                  P.S. I couldn't find a cute emoticon to use in this message. Perhaps I should seek your guidance on this useful feature next time.

                                                                   

                                                                  Thank you

                                                                  • 31. Re: Reusing a Date object.
                                                                    Lopo Nopo Level 1

                                                                    Haha ok this became fun here

                                                                     

                                                                    rtalton: It's "him".

                                                                     

                                                                    Gordon: I'm glad to see an Adobe guy who really try to assist like you, thanks!

                                                                     

                                                                    Ansury: Where did you come from?

                                                                     

                                                                    About the Timer idea by Gordon, it's an idea but not for my purpose;

                                                                    In short: It's a TCP/IP client program that sends a "keep-alive" packet every X seconds. In order to save this one packet it marks each last Socket::Send() with a timestamp, saving the time value at a shared variable.

                                                                    When the time to send the "keep-alive" packet arrives, the function checks if the last packet was sent before or less than X seconds, and if it was then no "keep-alive" is needed. To check that, this function also needs to 'getTime()' in order to compare the time.


                                                                    Maybe I'll think of something with this Timer idea, who knows, it sounds like it has some potential !

                                                                     

                                                                     

                                                                     

                                                                    About the 'delete' keyword;

                                                                    I use it to delete indexes at a Dictionary object.

                                                                     

                                                                    Now I know GC is a good thing but sometimes it's better to have control over it, therefore we do need this small feature called 'delete'.

                                                                     

                                                                    I must express my own feeling that AS3 isn't mature as C++ and whoever said that (or something like that) has probably never stood in front of a real complicated project.

                                                                     

                                                                    Anyway making a new Date object doesn't seem to consume (alot) so it's not the end of the world or something..

                                                                    • 32. Re: Reusing a Date object.
                                                                      Ansury Level 3

                                                                      rtalton- Huh? You shouldn't take it personally, just acknowledge a correction or correct a typo if it is one.

                                                                      rtalton wrote:

                                                                       

                                                                       

                                                                       

                                                                      re-use a previously used date object like this:

                                                                      myOldDateObject = new Date();

                                                                       

                                                                      I'm sorry if I hurt your feelings or you felt insulted, but this statement is just wrong.  I just don't like seeing someone making a simple and needed correction to obvious misinformation being given a three paragraph lecture about why they shouldn't have made the correction and why they shouldn't teach people or something.  I actually did respond to the part of the OP's question that I hadn't seen answered yet, the question about the delete keyword. If it was already answered amongst your back-and-forth, then sorry for the repeat I guess.

                                                                       

                                                                      I don't know what has changed but Adobe's forums seem to have become a much more adversarial place ever since this crap Jive upgrade went through with it's fancy (useless) features, and I don't like it at all.

                                                                      • 33. Re: Reusing a Date object.
                                                                        Ansury Level 3

                                                                        Lopo Nopo wrote:

                                                                         

                                                                         

                                                                        About the 'delete' keyword;

                                                                        I use it to delete indexes at a Dictionary object.

                                                                         

                                                                        Now I know GC is a good thing but sometimes it's better to have control over it, therefore we do need this small feature called 'delete'.

                                                                         

                                                                        I must express my own feeling that AS3 isn't mature as C++ and whoever said that (or something like that) has probably never stood in front of a real complicated project.

                                                                         

                                                                        Anyway making a new Date object doesn't seem to consume (alot) so it's not the end of the world or something..

                                                                         

                                                                        My take on this (and it's coming more from a Java perspective since I'm more familiar there but AFAIK the Flash VM works similarly):

                                                                         

                                                                        The optimization done in these languages's JIT (just in time) compilers make them a different beast than a C++ app.  I didn't want to buy into this at first either but from what I've always read, the optimizers are complex and smart enough that when developers do things they think are speeding things up, it can often have the opposite effect.  For example (theoretical), perhaps the optimizer knows that deleting 1000 date objects in memory all at once in a single operation is slightly faster than deleting each one separately, 1000 times.  Imagine if this were the case and a developer deletes each object as soon as they don't need it anymore.

                                                                         

                                                                        If their purpose was to conserve memory, again if it's functioning anything like a Java VM, releasing that memory doesn't speed up anything from the operating system's perspective because the VM will hold onto the memory it was previously allocated anyway.  Briefly put, generally speaking developer optimizations = teh suck, and compiler optimizations = better.

                                                                         

                                                                        I do think the memory management stuff in C++ was fun because of the tricks you could do and things, but that probably should stay in C++ world.

                                                                        • 34. Re: Reusing a Date object.
                                                                          meshgraphics Level 2

                                                                          Re Just In Time Compiling

                                                                           

                                                                          Keep in mind that JIT compiling is still compiling.  The 1000 date objects are created and removed at run-time.

                                                                           

                                                                           

                                                                          --== I think we need to hand out the Paris Hilton Awards for the Flex Group ==--