0

I'm planning on enforcing a rule in my project to write the codes for a single filter or hook in a single function for easier code maintenance, so instead of having

add_filter('wp','function_a');
function_a() {
    //code A goes here
}

add_filter('wp','function_b');
function_b() {
    //code B goes here
}

It will be reduced to:

add_filter('wp','function_ab');
function_ab() {
    //code A goes here
    //code B goes here
}

My question is, is there also a significant performance benefit by doing this?

  • Sorry my title is about disadvantage and yet I only asked for benefits. I am interested in learning both advantages and disadvantages of doing this, thanks. – morcen Nov 19 '17 at 3:16
  • 1
    I don’t see how this makes maintenance easier at all. Now you have one monolithic function that does many things. That’s textbook hard to maintain code. Functions should have a single purpose only. – Jacob Peattie Nov 19 '17 at 3:39
  • 2
    In short, there won't be any naked performance improvements with the second style of coding. – bravokeyl Nov 19 '17 at 4:04
1

Creating a program should be a balanced on how the efficiency of the code work and how easy for future maintenance.

For programming efficiency, both style 1 and style 2 of your code is not make a huge impact much. Because of in nowaday PHP, it converts the code into the bytecode only one time, and read it when visitor using it. So the performance is almost the same.

For future maintenance, it's depend on your team style of coding. Pick one that you more understand on it. For me, the first style is more practical because 1 function do only 1 job and it's much easier for maintenance. That's is.

1

Adding callbacks is basically free. Add this to your functions.php or create a new plugin for it.

timer_start();
$test = new test();
add_filter( 'all', [ $test, 'all' ] );
add_action( 'shutdown', [ $test, 'shutdown' ] );
class test {
  protected $num = 0;
  function all( $var ) {
    $this->num = $this->num + 1;
    return $var;
  }
  function shutdown() {
    var_dump( $this->num );
    var_dump( timer_stop() );
  }
}

Notice the number of callbacks (the first number var_dumped). It will probably be in the hundreds or thousands. Now remove the all filter. The second number dumped will decrease, and by a noticeable number, but still remarkably small.

When I tried this on my box, I had around 3000 callbacks that fired. When then all filter was added, it took around 0.02s to render and when it wasn't added, it took about 0.01s to render. So adding 3000 callbacks made the page render 0.01s slower. If you're Google, that makes a huge difference. But you're not, so it doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.