Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Object Caching performance

Is there difference between caching PHP objects on disk rather than not? If cached, objects would only be created once for ALL the site visitors, and if not, they will be created once for every visitor. Is there a performance difference for this or would I be wasting time doing this?

Basically, when it comes down to it, the main question is:

Multiple objects in memory, PER user (each user has his own set of instantiated objects)

VS

Single objects in cached in file for all users (all users use the same objects, for example, same error handler class, same template handler class, and same database handle class)

like image 656
Nikko Avatar asked Aug 09 '26 01:08

Nikko


2 Answers

To use these objects, each PHP script would have to deserialize them anyway. So it's definitely not for the sake of saving memory that you'd cache them on disk -- it won't save memory.

The reason to cache these objects is when it's too expensive to create the object. For an ordinary PHP object, this is not the case. But if the object represents the result of an costly database query, or information fetched from a remote web service, for instance, it could be beneficial to cache it locally.

Disk-based cache isn't necessarily a big win. If you're using PHP and concerned about performance, you must be running apps in an opcode-caching environment like APC or Zend Platform. These tools also provide caching you can use to save PHP objects in your application. Memcached is also a popular solution for a fast memory cache for application data.

Also keep in mind not all PHP objects can be serialized, so saving them in a cache, whether disk-based or in-memory, isn't possible for all data. Basically, if the object contains a reference to a PHP resource, you probably can't serialize it.

like image 161
Bill Karwin Avatar answered Aug 10 '26 16:08

Bill Karwin


Is there difference between caching PHP objects on disk rather than not?

As with all performance tweaking, you should measure what you're doing instead of just blindly performing some voodoo rituals that you don't fully understand. When you save an object in $_SESSION, PHP will capture the objects state and generate a file from it (serialization). Upon the next request, PHP will then create a new object and re-populate it with this state. This process is much more expensive than just creating the object, since PHP will have to make disk I/O and then parse the serialized data. This has to happen both on read and write.

In general, PHP is designed as a shared-nothing architecture. This has its pros and its cons, but trying to somehow sidestep it, is usually not a very good idea.

like image 35
troelskn Avatar answered Aug 10 '26 16:08

troelskn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!