gpt4 book ai didi

php - SimpleXML 与 DOMDocument 性能对比

转载 作者:可可西里 更新时间:2023-11-01 12:44:38 25 4
gpt4 key购买 nike

我正在使用 SimpleXML 类构建 RSS 解析器,我想知道使用 DOMDocument 类是否会提高解析器的速度。我正在解析一个至少有 1000 行的 rss 文档,并且我使用了这 1000 行中的几乎所有数据。我正在寻找完成时间最短的方法。

最佳答案

SimpleXMLDOMDocument 都使用相同的解析器 (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 文档。您的减速不会出现在内存使用或解析速度上,而是出现在您的应用程序逻辑上。

关于php - SimpleXML 与 DOMDocument 性能对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com