Make WordPress Core


Ignore:
Timestamp:
09/18/2023 12:39:18 PM (18 months ago)
Author:
spacedmonkey
Message:

Plugins: Store result of call to array_keys, to save repeated calls in WP_Hook class.

In the WP_Hook class the function array_keys was called every time an array of hook priorities was needed. For sites with lots of filters or actions, this would result in thousands of calls to the array_keys function, which uses server resources. Instead of recomputing this array every time it is needed, only compute it when filters are added and removed, then store the result as a class property. Improve unit tests to ensure this behaviour is tested.

Props spacedmonkey, bor0, flixos90, hellofromTonya, mukesh27.
Fixes #58458.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/hooks/removeAllFilters.php

    r53804 r56609  
    1919
    2020        $hook->remove_all_filters();
     21        $this->check_priority_non_existent( $hook, $priority );
    2122
    2223        $this->assertFalse( $hook->has_filters() );
     
    3536
    3637        $hook->remove_all_filters( $priority );
     38        $this->check_priority_non_existent( $hook, $priority );
    3739
    3840        $this->assertFalse( $hook->has_filter( $hook_name, $callback_one ) );
    3941        $this->assertTrue( $hook->has_filters() );
    4042        $this->assertSame( $priority + 1, $hook->has_filter( $hook_name, $callback_two ) );
     43        $this->check_priority_exists( $hook, $priority + 1 );
     44    }
     45
     46    protected function check_priority_non_existent( $hook, $priority ) {
     47        $priorities = $this->get_priorities( $hook );
     48
     49        $this->assertNotContains( $priority, $priorities );
     50    }
     51
     52    protected function check_priority_exists( $hook, $priority ) {
     53        $priorities = $this->get_priorities( $hook );
     54
     55        $this->assertContains( $priority, $priorities );
     56    }
     57    protected function get_priorities( $hook ) {
     58        $reflection          = new ReflectionClass( $hook );
     59        $reflection_property = $reflection->getProperty( 'priorities' );
     60        $reflection_property->setAccessible( true );
     61
     62        return $reflection_property->getValue( $hook );
    4163    }
    4264}
Note: See TracChangeset for help on using the changeset viewer.