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.

Performance matters

There are some false myths about performance. One of the most famous is the idea about code optimization. That's wrong. Another myth is the client-side tuning for better results. Wrong too. I've seen many sites with a gnarly and messy code, absolutely lazy in their implementation and non-standard. Result? They weren't slow, even when I used to surf the web with a 800kbs/1Mb connection. What's more, these sites hosted forums, aggregators, and other database-driven applications. And they weren't slow. So what's the point? Bandwidth, server hardware like processor, memory, and other tweaks. In a nutshell: if you want an optimum performance, you should find some good server and a dedicated hosting. Forget all the stuff about shared hosting: that's poor, unsecure and limited. With a little more funds, you'll spare some additional issues.