Is calling function_exists() faster or slower that apply_filters()

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.

4 Answers
4

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:

<?php
if ( ! function_exists( 'taco_party' ) ) {
    function taco_party( $salsa = true ) {
        return $salsa;
    }
}

function taco_party( $salsa = true ) {
    return $salsa;
}
?>

Versus This:

<?php
function taco_party( $salsa = true ) {
    return apply_filters( 'taco-party', $salsa );
}
function hot_salsa() {
    $salsa = true;
    return $salsa;
}
add_filter( 'taco-party', 'hot_salsa' );
?>

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.

Leave a Comment