No need to DESTROY objects

Share this topic:



Link to this posting

Postby Ursego » 19 Feb 2013, 22:24

Don't DESTROY objects if that requires extra efforts. Don't waste time for memory management if a CREATEd object is passed to another function or object - trust on garbage collector.

In our days, there is no need to destroy previously created objects - the garbage collector will clean the memory for you. GC is a great invention! Now we are not afraid of visitation of God if we disobey the rule "destroy in the same script where created" - we simply don't think about destroys at all, concentrating on more important stuff. We can pass the created object to another function (even POSTed!) or object (for example, using OpenWithParm()) and forget about memory leaks!

But garbage collection also helps to make code more elegant and even more efficient. How? In a few ways:

1. If you destroy an object in your code then the memory is being freed just when the program flow comes to the destroy command. Are you sure the time must be spent on this operation exactly in this moment? And if your whole script performs a time-consuming operation? And if you destroy a few objects? And if you check with IsValid() before destroys? Oppositely to all that, GC will free the memory when the application is inactive, so the user will not experience any decline in performance.

2. Less lines of code (sometimes we had a number of destroy commands, ornamented with if IsValid()...).

3. Before the garbage collection era, if we wanted to exit a function a few times (i.e. to write return in different parts of the script), we had to destroy our garbage objects before EACH return. If we wanted to write all the destroys and the return only once (in the end of the script), then we had to keep the track with a specially created local Boolean success/failure flag - that meant not only more lines of code but also one more tab of indentation.


REMARK: Of cource, there can be situations when the memory should be managed by you. For example, trusting on GC can cause problems if objects are created in a loop - theoretically, the memory can explode before the garbage is automatically collected).
User avatar
Ursego
Site Admin
 
Posts: 111
Joined: 19 Feb 2013, 20:33

Return to Elegant Code

Who is online

Users browsing this forum: No registered users and 1 guest


No need to DESTROY objects

Share this topic:


If you think that this site is not too bad, please LIKE it in Facebook. Thanks!





cron
free counters

eXTReMe Tracker