xml vs json (v3)

Revision 3 of this benchmark created by Heavensrevenge on


Preparation HTML

<script src="https://code.jquery.com/jquery-git2.min.js"></script>

<script>
// Changes XML to JSON
function xmlToJson(xml) {
  
  // Create the return object
  var obj = {};

  if (xml.nodeType == 1) { // element
    // do attributes
    if (xml.attributes.length > 0) {
    obj["@attributes"] = {};
      for (var j = 0; j < xml.attributes.length; j++) {
        var attribute = xml.attributes.item(j);
        obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
      }
    }
  } else if (xml.nodeType == 3) { // text
    obj = xml.nodeValue;
  }

  // do children
  if (xml.hasChildNodes()) {
    for(var i = 0; i < xml.childNodes.length; i++) {
      var item = xml.childNodes.item(i);
      var nodeName = item.nodeName;
      if (typeof(obj[nodeName]) == "undefined") {
        obj[nodeName] = xmlToJson(item);
      } else {
        if (typeof(obj[nodeName].length) == "undefined") {
          var old = obj[nodeName];
          obj[nodeName] = [];
          obj[nodeName].push(old);
        }
        obj[nodeName].push(xmlToJson(item));
      }
    }
  }
  return obj;
};
</script>

Setup

testxml = '<svg>';
  for (i = 0; i < 1000; i++) {
     testxml += "<polyline id='i" + i + "'></polyline>";
  }
  testxml += '</svg>';
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(testxml, "text/xml");
  jsonDoc = xmlToJson(xmlDoc);

Test runner

Ready to run.

Testing in
TestOps/sec
Traverse XML DOM
idString = '';
$(xmlDoc).children().children().each(function(i,p) { 
   idString += ' ' + p.getAttribute('id'); 
});
ready
Traverse JSON
obj = jsonDoc.svg.polyline;
objlen = obj.length;
idString = '';
for (i = 0; i < objlen; i++) {
   idString += ' ' + obj[i].id;
}
ready
Convert XML > JSON and Traverse JSON
jsonDoc = xmlToJson(xmlDoc);
obj = jsonDoc.svg.polyline;
objlen = obj.length;
idString = '';
for (i = 0; i < objlen; i++) {
   idString += ' ' + obj[i].id;
}
ready
Traverse XML with different id lookup
idString = '';
$(xmlDoc).children().children().each(function(i,p) { 
   idString += ' ' + p.attributes.item(0).nodeValue; 
});
ready
Traverse XML with jQuery attribute get
idString = '';
$(xmlDoc).children().children().each(function(i,p) { 
   idString += ' ' + $(p).prop('id');
});
ready
Traverse XML with jQuery direct attribute get
idString = '';
$(xmlDoc).children().children().each(function(i,p) {
   idString += ' ' + this.id;
});
ready
Traverse XML without jQuery
idString = '';
chld = xmlDoc.childNodes.item(0).childNodes;
objlen = chld.length;
for (i = 0; i < objlen; i++) {
   idString += ' ' + chld.item(i).getAttribute('id');
};
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.