[wp-trac] [WordPress Trac] #18230: Optimize wp_list_pluck

WordPress Trac wp-trac at lists.automattic.com
Sat Jul 23 20:18:21 UTC 2011


#18230: Optimize wp_list_pluck
-------------------------+-----------------------------
 Reporter:  Otto42       |      Owner:
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  Performance  |    Version:
 Severity:  normal       |   Keywords:
-------------------------+-----------------------------
 wp_list_pluck is a bit slow when dealing with objects, due to the array
 cast. Since we mostly use objects, this is a problem.

 Proof code of a speedup enhancement:

 {{{
 function old_wp_list_pluck( $list, $field ) {
         foreach ( $list as $key => $value ) {
                 $value = (array) $value;
                 $list[ $key ] = $value[ $field ];
         }

         return $list;
 }

 function new_wp_list_pluck( $list, $field ) {
         foreach ( $list as $key => $value ) {
                 if (is_object($value)) $list[$key] = $value->$field;
                 else $list[$key] = $value[ $field ];
         }

         return $list;
 }

 // tested on a site with about 40 tags in the DB
 $terms = get_terms('post_tag');

 // run both old an new code 10000 times and measure the differences

 $start = microtime(true);
 for ($i = 1; $i <= 10000; $i++) {
         old_wp_list_pluck($terms,'name');
 }
 $end = microtime(true);
 var_dump($end - $start);

 $start = microtime(true);
 for ($i = 1; $i <= 10000; $i++) {
         new_wp_list_pluck($terms,'name');
 }
 $end = microtime(true);
 var_dump($end - $start);
 }}}

 Result:

 float(0.85771203041077)
 float(0.36069202423096)

 New version is slightly more than twice as fast.

 Patch forthcoming.

-- 
Ticket URL: <http://core.trac.wordpress.org/ticket/18230>
WordPress Trac <http://core.trac.wordpress.org/>
WordPress blogging software


More information about the wp-trac mailing list