简体   繁体   English

重用DOMDocument或创建一个新的DOM对性能的影响

[英]Performance Implications of Reusing DOMDocument Or Creating a New One

Let's say you have a page that has multiple ( 12 ) invocations of this innerHTML function: 假设您有一个页面,该页面具有此innerHTML函数的多个(12)调用:

<?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. 这将导致制作12个DOMDocuments。 Would it be worth it to save a reference to 1 DOMDocument and constantly clean it out per usage? 保存对1个DOMDocument的引用并根据使用情况不断对其进行清理是否值得? If so, what would be the most efficient method of cleaning it? 如果是这样,最有效的清洁方法是什么?

Why not just create a DomDocumentFragment ? 为什么不创建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). 就性能水平而言,每个调用大约花费0.00005秒,与使用哪个功能无关(彼此之间有一定的误差)(基于快速测试)。 So don't worry too much about it, but also don't do it more than necessary... 因此,不必对此太担心,也不要做超出必要的事情...

I don't think there's any performance issues; 我认为没有任何性能问题; DOMDocument isn't parsing any XML upon creation. DOMDocument在创建时不会解析任何XML。 The most processing intensive operation in the whole thing I think is saveHTML() , so you wouldn't save anything by using the same DOMDocument . 我认为整个过程中处理最密集的操作是saveHTML() ,因此您不会通过使用相同的DOMDocument来保存任何内容。

Destroying the object and creating a new one is likely more efficient than keeping a global variable and emptying it upon every use. 销毁对象并创建一个新对象可能比保留全局变量并在每次使用时将其清空的效率更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM