Skip to:
Content

BuddyPress.org


Ignore:
Timestamp:
02/05/2016 02:41:22 AM (11 years ago)
Author:
boonebgorges
Message:

Improve performance of bp_sort_by_key().

bp_sort_by_key() originally used create_function() to allow sorting by
dynamic $type and $key. However, create_function() has a tendency to
perform poorly. PHP 5.3 anonymous closures are much faster, but are unavailable
as long as we support PHP 5.2. So we introduce a new class that plays a role
similar to an anonymous closure, with a similar speed benefit.

Fixes #6864.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/bp-core/bp-core-functions.php

    r10497 r10514  
    119119 */
    120120function bp_sort_by_key( $items, $key, $type = 'alpha' ) {
    121         usort( $items, create_function( '$a, $b', '
    122                 $values = array( 0 => false, 1 => false, );
    123                 $func_args = func_get_args();
    124                 foreach ( $func_args as $indexi => $index ) {
    125                         if ( isset( $index->' . $key . ' ) ) {
    126                                 $values[ $indexi ] = $index->' . $key . ';
    127                         } elseif ( isset( $index["' . $key . '"] ) ) {
    128                                 $values[ $indexi ] = $index["' . $key . '"];
    129                         }
    130                 }
    131 
    132                 if ( isset( $values[0], $values[1] ) ) {
    133                         if ( "num" === "' . $type . '" ) {
    134                                 $cmp = $values[0] - $values[1];
    135                         } else {
    136                                 $cmp = strcmp( $values[0], $values[1] );
    137                         }
    138 
    139                         if ( 0 > $cmp ) {
    140                                 $retval = -1;
    141                         } elseif ( 0 < $cmp ) {
    142                                 $retval = 1;
    143                         } else {
    144                                 $retval = 0;
    145                         }
    146                         return $retval;
    147                 } else {
    148                         return 0;
    149                 }
    150         ') );
     121        usort( $items, array( new BP_Core_Sort_By_Key_Callback( $key, $type ), 'sort_callback' ) );
    151122
    152123        return $items;
Note: See TracChangeset for help on using the changeset viewer.