Dev tip: Speeding it up :D
-
Hi Rahul,
I saw some comments on this plugin’s speed.
I’ve done a lot of benchmarking in the past year on PHP and I want to give you some of my findings. I hope you find it helpful!As I’m obsessed with that (as you might already know), and with over 500 hours of optimizing done in the past year, and as I also work with your plugin, I want to give you this freebie.
You know the function
is_anspress()? It’s quite heavy and called 25 times throughout the plugin.Below is a modified version of that function, including all the speed-up’s I’m listing below.
You can cache its outcome, so it will only run once, and then returns a cached boolean, which only takes about 50 bytes of cache and ~30 CPU cycles (instead of a tens of thousands).
It’s called staticvar caching (or so I’ve read somewhere).
Feel free to apply this method on other “static” functions (which don’t change over the course of the load).Other improvements include using a triple “=” instead of a double “=”, which will prevent multiple checks on a variable as it also checks for the type. using “!==” instead of “!=” will yield the same result.
It will give about 6% performance improvement, on the finer details.function_existsis the true killer of performance, as PHP has to look back and compare in its function memory. So be sure to cache those checks in functions if you use them a lot.Combining statements will save you some memory, and sometimes allow you to remove the flip sign ( “!” ).
The following code contains all the improvements combined. I’m sure this will speed things up!
function is_anspress() { // Setup cache. This value can change throughout the function. static $cache = null; // Check if cache is filled in (not null) and return if found without altering. if ( isset( $cache ) ) return $cache; $queried_object = get_queried_object(); // if buddypress installed (the heavy part, put in different cache) if ( bp_current_component_exists() ) { $bp_com = bp_current_component(); if ( 'questions' === $bp_com || 'answers' === $bp_com ) { return $cache = true; } } // Combined minor improvement if ( isset( $queried_object->ID ) && $queried_object->ID == ap_opt( 'base_page' ) ) { return $cache = true; } // Tell cache it's false return $cache = false; } // Cached heavy check function bp_current_component_exists() { static $cache = null; if ( isset( $cache ) ) return $cache; return $cache = function_exists( 'bp_current_component' ); }Keep adding these kinds of improvements throughout the plugin, like with
is_question(), and I’m sure your plugin will be super speedy!Through parameters you can disable cache. Feel free to browse my code for more staticvar examples :).
I hope this helps, if you have any more questions, you know where to find me!
Have a great day and keep up the good work Rahul!
I’m sure a lot of users will be very happy with these kinds of improvements (and they’re fun to write too!) 🙂
The topic ‘Dev tip: Speeding it up :D’ is closed to new replies.