开发者

XML Parsing vs DOM Implementation create methods

I remember well that using the DOM implementation to create new HTML elements on a document was considered to be very much slower than assigning an HTML string to the 'innerHTML' property of the applicable HTML element.

Does the same apply when authoring XML documents using JavaScript? Rather than using the DOM implementation's various create methods, would it be faster to just generate the XML string and parsing it?

Just something I wondered about.... :)

*EDIT - Added an example *

Which is faste开发者_开发技巧r? (I'll be using jQuery's parseXML function to do the parsing example):

var myXdoc = $.parseXML("<person><name>Bob</name><relation>Uncle</relation>");

Or

var myXdoc

if (window.ActiveXObject) {
    myXdoc = new ActiveXObject("Microsoft.XMLDOM");
    myXdoc.async = false;
}
else if (document.implementation && document.implementation.createDocument)
    myXdoc = document.implementation.createDocument("", "", null);

var p = myXdoc.documentElement.appendChild(myXdoc.createElement("person"));
var n = p.appendChild(myXdoc.createElement("name"));
n.appendChild(myXdoc.createTextNode("Bob"));
var r = p.appendChild(myXdoc.createElement("relation"));
r.appendChild(myXdoc.createTextNode("Uncle"));


The first thing we have to know why createDocument() might be slow. The reason is that the DOM is alive and if you are modifying it, it triggers a re-validation of the DOM tree and probably a redraw of the site. Every time. But we could avoid this unnecessary re-validation and re-draw by using createDocumentFragment(). The DocumentFragment isn't part of the DOM and so it wont trigger any events. So you can build your complete DOM part and in the last step append it to the DOM tree. I think it's the fastest way to create large DOM parts.

UPDATE I tested it in Firefox 7 using Firebug. The code:

console.time("a");
for(var i=0; i<1000; i++) {
$.parseXML("<person><name>Bob</name><relation>Uncle</relation></person>")
}
console.timeEnd("a");

console.time("b");
for(var i=0; i<1000; i++) {
var myXdoc
if (document.createDocumentFragment) {
    myXdoc = document.createDocumentFragment();
}
var p = myXdoc.appendChild(document.createElement("person"));
var n = p.appendChild(document.createElement("name"));
n.appendChild(document.createTextNode("Bob"));
var r = p.appendChild(document.createElement("relation"));
r.appendChild(document.createTextNode("Uncle"));
}
console.timeEnd("b");

The result: "a" about 140ms and "b" about 35ms. So the string parse version is slower.

UPDATE2 It's very likely that the second variant is faster in any other browser, too. Because the parse method has to build the DOM object too and it's very likely that it uses the same methods (e.g.: document.createElement). So the parse method can't be faster. But it's slower because it has first to parse the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜