The Flash API provides a very nice set of XML classes along with syntax sugar in its E4X implementation. You can use this to not only read XML that you download, but also to write out XML that you upload. Unfortunately, it turns out that this is horrifyingly slow. Today we’ll do a little experiment to exemplify this.

The XML, its sister class XMLNode, and the many E4x syntax sugar operators AS3 provides for you sure do make using XML clean, clear, and easy. In addition to the ease-of-use functionality, you get the flexibility of simply changing your pretty printing, easy reading back from your written XML, and a lot more flexibility to insert content wherever you need it. But let’s see the cost of all this with a simple test app:

const NUM_STUDENTS:int = 1000;
var i:int;
var beforeTime:int = getTimer();
var studentsXML:XML = <students/>;
for (i = 0; i < NUM_STUDENTS; ++i)
	var student:XML = <student/>;
	var firstName:XML = <firstName/>
	var lastName:XML = <lastName/>;
trace("XML Class Time: " + (getTimer()-beforeTime));
beforeTime = getTimer();
var studentsString:String = "<students>\n";
for (i = 0; i < NUM_STUDENTS; ++i)
	studentsString += "  <student>\n    <firstName>First" + i
		+ "</firstName>\n    <lastName>Last" + i + "</lastName>\n  </student>\n";
studentsString += "</students>";
trace("String Class Time: " + (getTimer()-beforeTime));

This simply builds a list of students using the XML and String classes, such as the list of students that may reasonably attend a middle school: 1000. If you’re used to seeing my test applications, you’re probably used to seeing huge numbers for the sake of amplifying performance differences. Unfortunately, the performance is so bad here that no such amplification was required:

Environment XML Class String Class Slowdown
2.2 Ghz Intel Core 2 Duo, 2GB RAM, Mac OS X 10.6 369 2 184.5x
3.0 Ghz Intel Core 2 Duo, 4GB RAM, Windows XP 229 1 229x
Average 206.75x

Ouch! Using the XML class to build even a simple XML file as this is over 200x slower than plain Strings! If you’re interested at all in performance, even in a non-critical part of your code, avoid using the XML class to build your XML. On a slower computer than mine, this may cause a full second skip in any animation or UI interaction, which is usually deemed unacceptable. If you absolutely must use the XML class to build your XML, you’ll need to really start adding complexity by splitting the creation across frames of animation. This will likely further widen the performance gap. Meanwhile, the lowly String class can build this XML document in a snap without any complications. It is clean and straightforward to implement with a String. So watch out for the XML class. It can be deadly slow.