I use the function uasort in my code several times. I use it to sort my 100-or-so users by a variety of criteria. Users are stored in a multidimensional array. A typical array of users looks a bit like this:
$users => array(
'username' => // The username key is always lowercase for case-insensitivity.
array (
'nick' => 'Username', // Case-ified username, for display purposes.
'lines' => 8631, // Number of lines spoken.
'words' => 27343, // Number of words said.
'chars' => 132596, // Number of characters said.
'sad' => 24,
'yell' => 132, // Various mildly-interesting stats.
'happy' => 4
)
);
Sorting by the number of lines goes off without a hitch with this:
function top_sort($a, $b) // Sort according to number of lines, in descending order.
{
return $b['lines'] - $a['lines'];
}
// Elsewhere...
uasort($users, "top_sort");
Execution of this code completes in a fraction of a second.
However, this slightly different code to sort according to the mildly interesting values takes a second (give or take 200ms) to complete for each uasort:
function interesting_sort($a, $b) // Sort according to number of lines, in descending order.
{
global $stattype;
return ($b[$stattype]/$b['lines']) - ($a[$stattype]/$a['lines']);
}
// Elsewhere...
uasort($users, "interesting_sort");
The global variable stattype is set in a foreach loop that iterates through all interesting stats. Removing the loop and global variable, then hardcoding each uasort has no effect. Removing all but one interesting stat after that has no effect. What could be causing such a huge performance hit? The only difference I can see is that the second snippet accesses and extra array value and divides the two. Is something so trivial the source of the problem here?