Question

I'm currently making a behavior that uses a plugin model internally.

Every time I need to look for a reference I use:

$this->Viewed = ClassRegistry::init('Viewed.Viewed');

So it will init the model that holds the data. It's a good idea to use

$this->Viewed = ClassRegistry::removeObject('Viewed.Viewed')

to save memory in the excecution time of the script? or will add more time? This behavior is used a lot in the code... so every gain is necesary.

Was it helpful?

Solution

Here's the code for CakePHP's ClassRegistry::removeObject($key) function:

 public static function removeObject($key) {
    $_this = ClassRegistry::getInstance();
    $key = Inflector::underscore($key);
    if (isset($_this->_objects[$key])) {
        unset($_this->_objects[$key]);
    }
}

Really all it's doing is unsetting the relevant key in an array the presumably holds all CakePHP's objects. The unset() function in PHP will not free up memory immediately, though PHP may reclaim that memory eventually. Since there's not much going on in ClassRegistry::removeObject() I wouldn't be too concerned with it taking up much more processing.

But keep in mind also that once a PHP script is finished being executed, memory will also be reclaimed. So there's not much point in calling ClassRegistry::removeObject() if you can only call it near the end of your script. PHP is not really designed for manual memory management like that. If memory really starts becoming an issue, you could also consider writing something external in another language that your application can call using exec().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top