Search code examples
phpoopcachingapc

What are the benefits of caching instances of a class?


I have an application in which I repeatedly use the same (big) class. Since I use AJAX for that App, I always have to create a new object of this class. Someone advised me to cache an instance of this class and use it whenever it is required (using apc in a php environment)

What are the benefits of it ? is it really saving some time ?

    $this->tickets_persist = unserialize(@apc_fetch("Tickets"));

    if (!$this->tickets_persist) {
            $this->tickets_persist = new Tickets_Persistance(); // Take long time
            apc_store("Tickets", serialize($this->tickets_persist));
    } 

Solution

  • The benefits are only really realized if you are dealing with a class that has an expensive instantiation cost. If there is things that take a lot of time, memory or other resource being done in the constructor of the class (for example: reading an XML sitemap and building a complex data structure to build your navigation.) you can dodge this by leveraging caching.

    It's also worth noting that resources (like database links and such) are not able to be cached and they would have to be re-established after the object is unserialized (here is where the __sleep and __wakeup magic method comes in).