XML attributes and Ajax performance

Although XML is not the fastest data exchange format in use with Ajax, there are a couple of gotchas that we have to bear in mind when parsing XML documents. For example, given the following XML document:

<?xml version="1.0" encoding="utf-8"?>

<contacts>
  <contact>
    <name>Gabriele</name>
    <email>gabriele.romanato@gmail.com</email>
  </contact>
  <!--more-->
</contacts>

In order to properly parse a document like this, we should write something like:

var contacts = root.getElementsByTagName('contact');

for (var i=0; i<contacts.length; i++) {
  var name = contacts[i].getElementsByTagName('name')[0].firstChild.nodeValue;
  var email = contacts[i].getElementsByTagName('email')[0].firstChild.nodeValue;
}

This may turn out to be very expensive, because every time you need to access a child element and its contents you have to perform the same tasks. What if there are several different XML element names? Simply put, performance will suffer. Instead, we can use XML attributes to minimize the impact of the DOM access:

<?xml version="1.0" encoding="utf-8"?>
<contacts>
  <contact name="Gabriele" email="gabriele.romanato@gmail.com" />
  <!--more-->
</contacts>

So we could write something like this:

var contacts = root.getElementsByTagName('contact');
for(var i=0; i<contacts.length; i++) {
  var name = contacts[i].getAttribute('name');
  var email = contacts[i].getAttribute('email');
}

The second version of our JavaScript code is much shorter and shows a significant reduction of calls to DOM methods. By doing so, the overall performance of our code will be much better.

Leave a Reply

Note: Only a member of this blog may post a comment.