[wp-trac] [WordPress Trac] #50223: Performance improvement: Avoid using array_unique() where possible

WordPress Trac noreply at wordpress.org
Fri May 22 08:53:55 UTC 2020


#50223: Performance improvement: Avoid using array_unique() where possible
-------------------------+-----------------------------
 Reporter:  aristath     |      Owner:  (none)
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  General      |    Version:
 Severity:  normal       |   Keywords:
  Focuses:  performance  |
-------------------------+-----------------------------
 We could improve performance by avoiding an expensive call to
 `array_unique( $array );` where possible.
 A more performant option is `array_flip( array_flip( $array ) );`

 How to test:
 {{{#!php
 <?php
 $array_size = 100000;
 $runs       = 10000;
 $test       = [];

 // Generate array.
 for ( $run = 0; $run < $array_size; $run++ ) {
         $test[] = rand( 0, 100 );
 }

 // Test array_unique().
 $time = microtime( true );
 for( $run = 0; $run < $runs; $run++ ) {
         $out = array_unique( $test );
 }
 $time = microtime( true ) - $time;
 echo 'Array Unique: ' . $time;

 // Test array_flip( array_flip() ).
 $time = microtime( true );
 for ( $run = 0; $run < $runs; $run++ ) {
         $out = array_flip( array_flip( $test ) );
 }
 $time = microtime( true ) - $time;
 echo 'Flip Flip: ' . $time;
 }}}

 In PHP 7.3 this prints the following:
 {{{
 Array Unique: 31.995715856552
 Flip Flip: 9.5911109447479
 }}}

 In previous PHP versions the difference is a lot more dramatic (in PHP 5.6
 `array_flip( array_flip() )` is up to 1000 times faster).

 Of course this can't be done in arrays where keys are arrays or objects,
 but in most cases I've seen we use `array_unique` with strings so we
 should see a performance gain.

 This may look like a micro-optimization, and it is. The goal is reducing
 carbon emissions, and if we manage to save even .1ms from each page-load,
 globally it adds up to a few tons of CO2.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/50223>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list