简体   繁体   中英

XML parsing speed up. PHP

I'm here to ask about some concepts that can make this process faster:

foreach($xml->results->concepts->concept as $value2){//This is the original game.
    $total_concepts++;
    foreach($xml1->results->concepts->concept as $value1){//This is similar game. 
        $total_similar_concepts++;
        if(strcmp($value2->name, $value1->name)==0){
            $comparisons++;
            break;
        }
    }
}

Essentially, I'm comparing each 'concept' of the original game to each 'concept' of each 'similar' games.

This algorithm takes about 11.6 seconds on average to complete. Is there something I can do to make this run faster? I was thinking that perhaps parsing it as xml wasn't the best I could do.

The XML parsing is very unlikely the reason for your problem. If it has to do with XML that it's probably I/O, meaning that it takes to long to fetch data from disk.

What you are doing is combining all elements in $xml with all elements in $xml2 which is an O(n^2) complexity problem. You can try to reduce complexity by making use of a hashmap, which is easy in php because you got associative arrays which are essentially hashmaps:

foreach($xml->results->concepts->concept as $value2) {
  $total_concepts++;
  $map[(string)$value2->name] = true;
}
foreach($xml1->results->concepts->concept as $value1) {
  $total_similar_concepts++;
  if (isset($map[(string)$value1->name]))
    $comparisions++;
}

In best case this gives you O(2n) complexity, much better than the previous version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM