Performance Implications of Reusing DOMDocument Or Creating a New One
Let's say you have a page that has multiple ( 12 ) invocation开发者_StackOverflow中文版s of this innerHTML function:
<?php
function innerHTML($node){
$doc = new DOMDocument();
foreach ($node->childNodes as $child)
$doc->appendChild($doc->importNode($child, true));
return $doc->saveHTML();
}
This would result in 12 DOMDocuments being made. Would it be worth it to save a reference to 1 DOMDocument and constantly clean it out per usage? If so, what would be the most efficient method of cleaning it?
I don't think there's any performance issues; DOMDocument
isn't parsing any XML upon creation. The most processing intensive operation in the whole thing I think is saveHTML()
, so you wouldn't save anything by using the same DOMDocument
.
Destroying the object and creating a new one is likely more efficient than keeping a global variable and emptying it upon every use.
Why not just create a DomDocumentFragment?
function innerHTML($node){
$fragment = $node->ownerDocument->createDocumentFragment();
foreach ($node->childNodes as $child) {
$fragment->appendChild($child);
}
return $node->ownerDocument->saveXml($fragment);
}
It has better semantic meaning IMHO, and also saves you from having to import the nodes into a new document (Which likely will be expensive depending on the number of children the node has).
As far as performance levels are concerned, each call took about 0.00005 seconds independent of which function was used (they were with a margin of error from each other)(based on a quick test). So don't worry too much about it, but also don't do it more than necessary...
精彩评论