Shurn the Awesomer
Speeding up CakePHP3

Speeding up CakePHP3

Written on Sun, 23 July 2017

Googled up how to speed up CakePHP and I noticed how little articles have reference to CakePHP3. While there are other articles written on how to speed up CakePHP2, there's none on CakePHP3 that I found. So I'm going to share about my experience trying to speed up CakePHP3.

Note that this article is specifically about CakePHP3 and not PHP in general. Google up on speeding up PHP for more ways to speed up your web application. Also, unless you are experience a lot of traffic on your website or you have some heavy-duty processing, this optimisation won't give you significant speed.

The Beauty and Curse of Automagic


One of the beautiful things about CakePHP3 is that it does a lot of automagic things for the developer so that you can rapidly prototype an application. The downside of it is that it uses a lot of processing power and a big lot of memory. I'm going to show you how you reduce CPU cycles and memory. Why memory? Simply because you wouldn't want your application start using swap space, which will drastically reduce your application speed.

Use Database Select


When we do a data retrieval, we would normally do this:

$this->Articles->find("all");

With CakePHP's automagic, we would get every single column. This adds to processing time, both on the database and CakePHP. You see, CakePHP will process all the columns according to the type, especially if it is a date or a datetime field. On top of that, it will be stored as an array. Learn more about how big PHP arrays really are and you will know why it storing huge datasets in array is a bad idea.

So what we should do is to select very specific columns that you really need in your application by:

$this->Articles->find("all", ["fields" => ["id", "title"]]);


or

$this->Articles->find("all")->select(["id", "title"]);

With this trick, you use less processing power from the database and PHP. You will certainly reduce memory usage by a significant factor, especially if your query returns a huge dataset.