Code Optimization

Just recently, I upgraded my local version of PHP to the latest – v7.3.6. I know this version comes with a list of optimizations and it’s much improved over previous versions. And so this got me thinking about code optimization and how I have learned to write PHP code over time.

Many years ago I did a presentation to my local WordPress meetup group, the OC WordPress Meetup, on PHP Code Optimization. This presentation eventually turned into a talk at the following Orange County WordCamp in 2014. I thought I’d dust off these old optimization techniques and see if they still hold true with the new PHP 7.x version. I know that PHP 7.x is dramatically faster than older versions so I want to see if any those old techniques still apply, or more importantly if things have changed.

I got a few chuckles during the talk when I was describing the number of times I ran some of these tests. Some were run ten million times and others billions of times. Part of this was to spend enough time running the code so that I could actually measure the amount of time it takes to run the test and have enough time to be able to see differences in techniques.

One of the comments I got was whether or not business of testing things a billion times made sense since WordPress and other frameworks don’t really work this way. And if there’s only a few microseconds time difference after a hundred million times, why bother?

My answer is that every framework is made up of thousands and thousands of lines of code. WordPress is no exception. It’s huge and getting bigger all the time. For any given page request, a lot of this code is executed. Some isn’t run of course. But if you’re using a coding technique that is demonstrably slower than another equivalent technique throughout this framework, there’s going to be a lot of time wasted. Multiply that by thousands of page views a day (which is everyone’s goal, right?) and your servers are working overtime for no reason. So to me, it doesn’t matter if you’re writing a small plugin, a medium sized theme or a very large plugin such as WooCommerce. Using more efficient code wherever you can will make your application run faster. If everyone did this for all the plugins, themes and core code, then everything will run faster.

So that’s my goal with this series of articles: get everyone replacing old slower coding techniques with more efficent techniques.

I don’t know how many articles will be in this series. But I’ll try to keep a list in this post updated so a reader can find the whole list from this one post. I will also throw in some Javascript and SQL optimization techniques as well just to keep things interesting.

Testing Methods: All tests will be done from the command line. This way we’ll be examining, as close as possible, the code being tested rather than a framework and the code.

Leave a Comment

Your email address will not be published. Required fields are marked *