I need help optimizing my usage of the usort
function because the solution that I came up with is taking much too long. Here is the code I have:
$xml = simplexml_load_file('topicMap.xtm');
$notion = $_GET['notion'];
$associations = $xml->xpath("/topicMap/association[role/topicRef/@href='" . $notion . "']");
usort($associations, function($a, $b) {
global $xml;
$a = ($xml->xpath("/topicMap/topic[@id='" . $a->role[0]->topicRef['href'] . "']"))[0]->name;
$b = ($xml->xpath("/topicMap/topic[@id='" . $b->role[0]->topicRef['href'] . "']"))[0]->name;
return strcasecmp($a, $b);
}
);
To explain: I load an xml file called "topicMap.xtm" and store it in the variable $xml
. From this large xml file (more than 1 million lines), I select, using the variable $notion
which I get via GET
, certain xml elements of type association and store them in the variable $associations
.
Now, I want to order these associations according to a name that is to be found, for each of the associations, elsewhere in the xml file (whereby this "elsewhere" is determined by the value of a @href
attribute contained in each association). Therefore, for each comparison operation between two associations that usort
performs, the large xml file is searched twice (with the xpath()
function).
This is taking very long. Here are a couple of performance statistics (number of associations: execution time in seconds):
2: 0.2 seconds
11: 2 seconds
47: 11 seconds
132: 41 seconds
297: 105 seconds
These execution times are not acceptable in my case. Is there a faster way to do what I want to do?
Thank in advance for your help!
source https://stackoverflow.com/questions/71163819/i-need-help-optimizing-the-usort-function
No comments:
Post a Comment