If you want to serve pages quickly and without using a lot of resources from the webserver to your users you need to code efficiently. One of the ways to do it is to use cache for somewhat static pages.

What is caching?

Well, if we are doing calculations, database connections and queries or external services usage, those will take time and resources from the server and might take time to load. Caching is the process of making the content once, and saving it ready to serve on a static file, which is much quicker to load and process.

One example that I recently worked with is processing and resizing images and even though I had access to a very strong server, using a cache version of the images sped things up by a factor of ten in load times, especially when I tried handling hundreds of images at a time.

What content is best for caching?

Obviously, we can try and cache any web page and content on the server, but the best pages that will actually benefit from it are those with the heavy calculations or database queries or like a wrote before, image processing. You can cache anything by default, just take under consideration that not all pages will be served quicker. One other major thing to keep in mind before we go and cache our site is to what extent our pages need to be fresh and updated. Caching is great, but if we need our content to be fresh for every user on every page load, just don’t cache it.

Lastly, but the most important thing about caching in the method I suggest below is that it does not suit pages after login, or with personal data. If you serve pages with sensitive information, or per user data, this method is not for you. Either way, if that is the case, I strongly suggest thinking if caching is really necessary, and if so, implementing it very carefully.

 

The script below shows how to easily use the ob_start command (output buffer) to generate a copy of the page, save it as a text file in a directory specific for purpose and checking whether it is needed to serve a fresh version or the page or use the cached one.

 

 

Leave a comment