Why caching is good
What is caching?
Basically is a way of saving computational power when a server that hosts an app is serving the same content several times, to several users. Our app would normally save the output of some internal work either on the server’s hard drive as files either in memory in order to be able to serve the same contents all over again much faster. Of course, the concept of thees savings include an expiring time, after which the saved content is generated again.
In web development caching is typically a good thing. For instance, on a heavily visited news site, where thousands of visitors see the same page probably in the same second even an one minute cache could save a tremendous amount of computing power.
So, this article is just a proof of concept. For this I have set a web host, I am using Nginx,PHP,MariaDB. I installed the Smarty templates engine, which has it’s own disk caching engine.
I created a config.php file which contains basic app configuration information like sql credentials and default caching time.
My functions.php file contains a Template() class that extends the Smarty() class, in fact it defines working folders for Smarty and enables caching. The other class SQLi() extends the mysqli() class in order to facilitate work with MySQL queries.
I also imported the Geonames database just to have some heavy contents in my database. So, all my template does is to show on the screen a huge array extracted form this database.
My index.php is very simple. First of all we count the execution time (I used this example to do that), Then I initialize my classes and I check to see if the template isn’t already cached.
If it is, I would just send it to the browser, if not I would query the database for my Informations and then send it to the browser. On the very bottom I would also show the execution time.
And some results:
As you could see on the screenshot, on the first execution it would take the server about 3 seconds to query the database, generate the page and then send it to the browser. On the second and third execution however the actual time to “generate” the page on the server was about 0.1 seconds, which is by far better. As you could see this page actually sends 17 MB of information to the browser.
In real world situations it is probably impossible to just send the whole page as a cached one, you have probably some bits of information that might change on every load of your web page, but in fact it is good to know about and even use some internal caching, at least for some areas of your web pages.