php – How to speed up the process of sorting dates

Question:

the pc_date_sort () function shown in the example shows how to sort dates.

function pc_date_sort($a, $b) {
    list($a_month, $a_day, $a_year) = explode('/', $a);
    list($b_month, $b_day, $b_year) = explode('/', $b);
    if ($a_year > $b_year ) return 1;
    if ($a_year < $b_year ) return -1;
    if ($a_month > $b_month) return 1;
    if ($a_month < $b_month) return -1;
    if ($a_day > $b_day ) return 1;
    if ($a_day < $b_day ) return -1;
    return 0;
}
$dates = array('12/14/2000', '08/07/1999', '08/10/2001');
usort($dates, 'pc_date_sort');
echo '<pre>';
print_r($dates);

During sorting, the usort () function often — each time it needs to compare two items — recalculates the values ​​returned by the sort function, which slows down the process.

Please help me optimize the code How to avoid unnecessary work?

Answer:

use the standard built-in class . It used to be necessary to mark their bicycles with dates.

  • the built-in datetime is written in C, it will be faster,
  • it is tested and will be safer
  • he offers more options than his bike

you can complement it by wrapping it in your class / function, inheriting (not tested)

createFromFormat () will create objects from your date format without any additional tweaks and manual line explodes

Scroll to Top