From: "Benjamin J. Tilly" Date: 2001-04-29T19:02:25+09:00 Subject: [ruby-talk:14400] RE: Does ruby have destructors that are easy to use? jfn@enteract.com (Jeremy Nelson) wrote: >While helping a friend convert a program from perl to ruby, he wanted to >know how to define a destructor for a ruby object. Ruby doesn't have reliable destruction mechanics. >We have already tried > > define_finalizer(object, proc {....}) > >but have observed that this has an unfortunate effect on performance. >The program creates many tens of thousands of objects, and using the >define_finalizer trick triples the time needed to run the program. >Another problem is that it appears the finalizer function is called only >when the object is garbage collected, and it does not seem to be known >for certain that the garbage collector runs right away as soon as the >last reference to an object is destroyed. The garbage collector behaviour is as documented. The performance drop seems extreme to me. >So my question is: is there a method that ruby calls when the last reference >to an object is removed; a so called "destructor" in other object oriented >languages? No, because Ruby does not use reference counting. Instead it uses garbage collection. The problem you are encountering is true for all languages that use GC. Reference counting lacks this limit, but has a set of other things that tend to go wrong. (eg It doesn't handle circular references, it is much harder to avoid the possibility of memory leaks.) Alternate strategies: 1. Use an ensure block to do your cleanup actions in the calling code. 2. Have the object accept an iterator, and then it can manage its own lifecycle. 3. Implement your own reference counting on the objects that need it so you know when to clean things up. FYI the decision to use GC rather than reference counting is also coming up again in the Perl world. Last I heard it was not yet decided how Perl 6 will work. (I have not been listening that closely though.) People want things (like running in a JVM) that are incompatible with reference counting, but people also don't want old code to break. Cheers, Ben