我正在使用 SimpleXML 类构建 RSS 解析器,我想知道使用 DOMDocument 类是否会提高解析器的速度。我正在解析一个至少有 1000 行的 rss 文档,并且我使用了这 1000 行中的几乎所有数据。我正在寻找需要最少时间完成的方法。
SimpleXML
and DOMDocument
两者都使用相同的解析器(libxml2
), 所以parsing它们之间的差异可以忽略不计。
这很容易验证:
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 文档。您的减速不会体现在内存使用或解析速度上,而是体现在您的应用程序逻辑上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)