Skip to content

Instantly share code, notes, and snippets.

@goetas
Created July 9, 2014 06:30
Show Gist options
  • Save goetas/a08227c9346f500bbb91 to your computer and use it in GitHub Desktop.
Save goetas/a08227c9346f500bbb91 to your computer and use it in GitHub Desktop.
PHP DOM XPath Test
<?php
$xml = new DOMDocument();
$xml->loadXML('
<a xmlns="http://www.aaa.bbb.cc/xx">
<b/>
<b xmlns:x="http://www.aaa.bbb.cc/xxyy">
<c xml:id="c" aa="a" bb="bb" xmlns:c="http://www.aaa.bbb.cc/xx">
<c:d/>
</c>
</b>
<b/>
<b/>
</a>
');
$e = $xml->getElementById("c");
$n = 10000;
$t = microtime(1);
echo "Iterate over attributes: ";
for ($i = 0; $i<$n; $i++){
foreach($e->attributes as $att){
$att->nodeName;
}
}
$t0 = microtime(1)-$t;
echo round($t0,4);
echo "\n\n";
$t = microtime(1);
echo "Iterate get each attribute: ";
for ($i = 0; $i<$n; $i++){
foreach($e->attributes as $att){
$e->getAttribute($att->nodeName);
}
}
$t3 = microtime(1)-$t;
echo round($t3,4)."s\n\t";
echo round($t3/$t0)."x slower than iteration over attributes\n\n";
$t = microtime(1);
echo "Reuse DOMXPath instance: ";
$xp = new DOMXPath($xml);
for ($i = 0; $i<$n; $i++){
foreach($xp->query('namespace::*', $e, false) as $att){
$att->nodeName;
}
}
$t2 = microtime(1)-$t;
echo round($t2,4)."s\n\t";
echo round($t2/$t0)."x slower than iteration over attributes\n\n";
$t = microtime(1);
echo "New DOMXPath instance: ";
for ($i = 0; $i<$n; $i++){
$xp = new DOMXPath($xml);
foreach($xp->query('namespace::*', $e, false) as $att){
$att->nodeName;
}
}
$t1 = microtime(1)-$t;
echo round($t1,4)."s\n\t";
echo round($t1/$t0)."x slower than iteration over attributes\n\n";
Iterate over attributes: 0.0179
Iterate get each attribute: 0.043s
2x slower than iteration over attributes
Reuse DOMXPath instance: 0.0802s
4x slower than iteration over attributes
New DOMXPath instance: 0.1584s
9x slower than iteration over attributes
@technosophos
Copy link

I would be curious whether the performance ratio stayed the same for a larger DOM. If some of the XPath overhead comes from compiling the XPath, then this might even out with an average or large DOM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment