Is calling function_exists() faster or slower that apply_filters() … or is the difference so small that it should not be considered?
I did a bit of testing based on Kaiser’s and it showed that function_exists() is ~3 times faster where both the function and filter exist. and ~11 times faster if the filter does not exist. Was not expecting this.
function taco_party() {
return true;
}
add_filter( 'taco-party', 'taco_party' );
timer_start();
for ( $i = 0; $i < 1000000; $i++ ) {
$test = apply_filters( 'taco-party', '' );
}
echo( 'Seconds: ' . timer_stop( 0, 10 ) . '<br />' );
timer_start();
for ( $i = 0; $i < 1000000; $i++ ) {
if ( function_exists( 'taco_party' ) ) {
$test = taco_party();
}
}
echo( 'Seconds: ' . timer_stop( 0, 10 ) . '<br />' );
Bear in mind that this is running each method 1,000,000 times which is quite a lot. Each method ran once completes very, very quickly:
Test 1: 0.0000491142
Test 2: 0.0000140667
I would conclude that the difference is not an issue.
I don’t know if one is faster or slower than the other, but I would suggest that using
apply_filters()
is the better approach, because it is cleaner, and more intuitive (in the sense of doing things the “WordPress way”).EDIT
If you’re doing comparison tests, shouldn’t you compare the time required to execute the following:
This:
Versus This:
It’s not just the time required to check for the existence of the function or filter, but rather the time required to do something.
WordPress has ~ 2.700 functions & ~ 250 attached actions in
global $wp_filter;
So the Q could be:
Imo filters/hooks are the faster way, more safe and easier to backtrace. My choice would be filters.
Ok, after running several tests1) I can see that
has_filter
takes ~ 20% more time to finish (on a not vanilla install) thanfunction_exists
:1) This is the code I used to test. It was set on the top of the functions.php file
You are talking about micro-optimizations here. Stick to apply_filters which is easier to use and allows the end user to also add content before/after your function output if they wanted without copying the entire function over if that’s all they want to do. Don’t be so concerned about possibly saving 0.000001 seconds on anything. Always focus on clean, easy to read and modular code. PHP keeps getting faster with each update and WordPress sites should be using caching functions anyway to return static code so micro-optimizing is just a waste of time and stress 😉