PHP Performance

Beyond the obvious API differences, the code structure for implementing WordPress plugins is different from coding for, say, applications. When an application is launched, typically the code will spend time setting up the objects and data structures to allow it to then quickly perform various user tasks. In WordPress, each HTTP GET request is independent of any other and thus is akin to “launching” and then quitting an application for each page view! It makes no performance sense spending time to initialize until you know what the user task is. Only initialize enough to know what the user task will be. As someone who previous to WordPress implemented application and server code, this is a very different structure and mindset.

In WordPress, the only data persistent between web page requests is that stored in the database (or cached by “external” functions). Static site generators are the current rage because they eliminate most of the WordPress and PHP overhead by serving “pre-assembled” web pages. While PHP is optimized to quickly do web page requests, plugin authors can do their part also.

For example, why spend time initializing to handle a short-code when the page being viewed doesn’t contain it? Do the minimum needed to register your handler and then postpone all other initialization until the first time your short-code is used. Use the singleton coding pattern along with autoloading of classes to do this. Wrapping most of your code in autoloading classes is an easy way to handle this. Same situation applies to REST API handlers and admin vs front-end code. WordPress recognizes the front-end and admin-panel distinction by providing separate “enqueue-script” handlers. If the user isn’t viewing the dashboard, why even incur the overhead loading the admin classes?

This separation of code registering your handlers from the code processing the requests is often foreign to object-oriented coders since they are used to wrapping all the functionality of an object in the same class (and file) and registering handlers in the class constructor. In WordPress, registering of handlers is often found in the global scope often at the bottom of a class definition file. By moving this global scope code to a separate file and autoloading the class definition file only when used provides a small performance gain. On its own, this is only a small performance gain, but since a site with many plugins can “suffer a death of a thousand cuts”, this can add up.