Saturday, May 17, 2008

anonymous function caching

As anyone who has dabbled with php create_function etc. will be able to tell you there are inherent memory leak issues with its implementation. From what I understand it does not apply garbage collection to them for one reason or another (I am going to research this further). Well here is the solution I have been using.

Define a directory where your anonymous methods will sit. I call mine 'defun'.

I have a method called fn($args,$body) which when called will make an md5 of the args+body, this is then prefixed with anon_ and called $name(as it could yield a name with a number as first character which is disallowed in php). I do a file_exists on $name to see if there is a file with that same name (and md5 fingerprint). If not I create it as a proper php file and close it. Then it does a require_once on $name and returns $name as this is what call back methods use to access it.

The only thing I have been worried about is the possibility of md5 collision? Anyway you see an increase of 100% the second time you run a script as it is just doing require_once instead of fwrites.

2 comments:

Chalain said...

Next week, on "When Greenspun Attacks"....

I did a lot of that sort of thing back in my PHP days. I knew I was in trouble when I was beginning every project by writing double dispatch for everything so I could embed function calls in the database....

I finally decided that the language just hurt too much and went off to look for green(spunn?)er pastures.

Good on you for this exercise. Don't get me wrong: I think you're crazy. But good on you all the same. :-)

shaunxcode said...

haha thanks. Yeah I am at any one time messing with Clisp, Smalltalk (seaside!!), python (django!).. and yes.. ruby but mainly in the context of google sketchup.

But in reality my day to day work is still in PHP so I figure I may as well try to make it as elegant and painless as possible.. right? Is that possible?