DB_DataObject's Memory Issues

December 14, 2005

We are using DB_DataObjects as the database abstraction layer for Maintain. It's a pretty convenient way to access databases, in most cases preventing you from writing ugly SQL strings at all. So far, so good.

However, when handling lots of database entries (in my case a couple of ten thousands), you might easily run into PHP's memory limit. Imagine the following scenario:

$books = DB_DataObject::Factory('books'); $books->type = 'novel'; $books->find(); while ($books->fetch()) {     do_something(); }

It will magically query your database for you, taking some memory for caching and, when you made your way through all of the returned records (what should actually happen at some time, considering that you have got a while clause here), it should destroy the cached information, setting the memory free that was used for it.

It does not.

Imagine the above code sample being inside another while() statement. It will start constantly leaking memory until it runs into PHP's memory limit. In my case, the script finally took 56 Megs of space.

The solution is to run $books->free() after you've iterated through the records, even though the associated man page claims: "DataObjects stores result sets as a private global variable, normally this is free'ed after you have run through the results, or at the end of the request.".

By that, I cut down the memory usage of my script to barely 3 1/2 megs. Sweet! :)

Update: Bug filed. Update 2: The bug was fixed and a new, stable release is available now. Go ahead and upgrade :)

Was this helpful? Buy me a coffee with Bitcoin! (What is this?)

Updating Adobe Flash Without Restarting Firefox

No reason for a Flash upgrade to shut down your entire browser, even if it claims so.It's 2015, and the love-hate relationship of the Web...… Continue reading

Reddit's Fail-Alien (or "Fail-ien?")

Published on January 15, 2015