[英]SimpleXML vs DOMDocument performance
我正在使用SimpleXML類構建RSS解析器,我想知道使用DOMDocument類是否會提高解析器的速度。 我正在解析一個至少1000行的rss文檔,我使用了來自這1000行的幾乎所有數據。 我正在尋找花費最少時間來完成的方法。
SimpleXML
和DOMDocument
都使用相同的解析器( libxml2
),因此它們之間的解析差異可以忽略不計。
這很容易驗證:
function time_load_dd($xml, $reps) {
// discard first run to prime caches
for ($i=0; $i < 5; ++$i) {
$dom = new DOMDocument();
$dom->loadXML($xml);
}
$start = microtime(true);
for ($i=0; $i < $reps; ++$i) {
$dom = new DOMDocument();
$dom->loadXML($xml);
}
$stop = microtime(true) - $start;
return $stop;
}
function time_load_sxe($xml, $reps) {
for ($i=0; $i < 5; ++$i) {
$sxe = simplexml_load_string($xml);
}
$start = microtime(true);
for ($i=0; $i < $reps; ++$i) {
$sxe = simplexml_load_string($xml);
}
$stop = microtime(true) - $start;
return $stop;
}
function main() {
// This is a 1800-line atom feed of some complexity.
$url = 'http://feeds.feedburner.com/reason/AllArticles';
$xml = file_get_contents($url);
$reps = 10000;
$methods = array('time_load_dd','time_load_sxe');
echo "Time to complete $reps reps:\n";
foreach ($methods as $method) {
echo $method,": ",$method($xml,$reps), "\n";
}
}
main();
在我的機器上我基本上沒有區別:
Time to complete 10000 reps:
time_load_dd: 17.725028991699
time_load_sxe: 17.416455984116
這里真正的問題是您正在使用的算法以及您正在使用的數據。 1000行不是一個大的XML文檔。 您的減速不會在內存使用或解析速度上,而是在您的應用程序邏輯中。
好吧,我在DomDocument
和SimpleXML
之間遇到了巨大的性能差異。 我有~15 MB的大XML文件,大約有50 000個元素,如下所示:
...
<ITEM>
<Product>some product code</Product>
<Param>123</Param>
<TextValue>few words</TextValue>
</ITEM>
...
我只需要“讀取”這些值並將它們保存在PHP數組中。 起初我嘗試過DomDocument
......
$dom = new DOMDocument();
$dom->loadXML( $external_content );
$root = $dom->documentElement;
$xml_param_values = $root->getElementsByTagName('ITEM');
foreach ($xml_param_values as $item) {
$product_code = $item->getElementsByTagName('Product')->item(0)->textContent;
// ... some other operation
}
該腳本在60秒后死亡, 最大執行時間超出錯誤。 解析了只有15000件50k的物品。
所以我將代碼重寫為SimpleXML
版本:
$xml = new SimpleXMLElement($external_content);
foreach($xml->xpath('ITEM') as $item) {
$product_code = (string) $item->Product;
// ... some other operation
}
一秒鍾后,一切都完成了。
我不知道這些函數是如何在PHP內部實現的,但在我的應用程序中(以及我的XML結構), DomDocument
和SimpleXML
之間確實存在巨大的性能差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.