Like this:

Related

Fine, but when these anonymous objects go out of scope, Perl will reclaim the memory for instances, but not for the classes (classes remain in the _ANON_ symbol table, together with references to the “singleton methods” that were defined in those classes). So abusing this technique, especially in long-lived processes, could yield to memory leaks.

This might have been true at one point, but it’s not anymore. Anonymous classes can be GCed just fine; I created 10000 of them (one at a time) and my process’s memory usage didn’t go up. This is with 5.10.

The way it works is that each instance of the anon-class will hold on to a reference to the metaclass (for the anon-class). So the metaclass (and the package it points too) will stay around as long as there is an instance around that needs it. Once all the instances are gone, then there will no longer be any references to the metaclass and the metaclass (and associated package) can be garbage collected.

So yes anon-classes do tidy up behind themselves. From Class::MOP::Class pod:

“Anonymous classes are destroyed once the metaclass they are attached to goes out of scope, and will be removed from Perl’s internal symbol table.”

However saying that I may have a bug MooseX::SingletonMethods because quick test here seems to suggest those anon classes hang around in the symbol table. I’ll write up some proper empirical tests at weekend to get to bottom of it.

About…..

My name is Barry Walsh. I'm a freelance IT consultant from London, UK. [more]

This blog is mostly about Perl programming because this is what I use and love (and occasionally hate!) for the majority of my working (and sometimes non-working) day.

Occasionally I will touch on other subjects like PostgreSQL, Mac OSX, UNIX, Linux, Ruby, jQuery, Javascript, XML and many more techie things that I also play with regularly. Other non techie aspects of my life may slip in now and again but I'll try and keep that to a minimum because its normally boring anyway :)