Tuning AJAX
by Dave Johnson
|
Pages: 1, 2
JavaScript
Since we are talking AJAX, I have to give a little time to JavaScript, which is the glue of the AJAX world. JavaScript is largely uncharted territory for many developers, and many have little idea about its inner workings, let alone how it changes across browsers -- which it can do dramatically. When dealing with an interpreted language like JavaScript, it always helps to remember the simple things like making expensive function calls inside loops and being aware of the complexity of various algorithms.
At the same time, there are things that developers should try to forget simply because JavaScript is a very different beast. In many OOP languages inheritance and member accessors are commonplace, but in JavaScript these can be expensive operations. Conventional object declaration in JavaScript, by specifying new Object() for example, can be slow compared to using the slightly less versatile anonymous object syntax as shown below. This is the approach that the popular Prototype AJAX framework takes.
Rather than
var Foo = new Object();
Foo.a = "100";
Foo.b = "200";
consider
Foo = {
a: "100",
b: "200"
}
When accessing values of objects it is also advisable to use the associative array notation (since every object in JavaScript is an associative array) rather than the property name:
alert(Foo.a);
versus
alert(Foo['a']);
XML
There are two other very important areas that need some attention when discussing AJAX performance. Asynchronous indicates that there is some sort of messaging aspect to AJAX and this depends on both the network and the application data; this is closely related to the X in AJAX, which is the ubiquitous XML data or document format. Network performance and data are intimately related, and this is one point where people like to claim the relatively verbose nature of conventional XML messages as a reason for not using XML in AJAX. But there are always more or less compact XML representations of domain- or application-specific data structures. In many cases the XML in your application can be redesigned to be easier to process. XML is a reasonable option for your AJAX application when dealing with large amounts of data that need to be filtered or sorted real-time in the browser using XSLT.
XSLT
If you are using XML data in your AJAX applications you are likely going to use XSLT. For intranets and the enterprise, AJAX applications may need to deal with SOAP or at least XML-based web services, in which case XSLT is a great fit. There are a few areas where XSLT can be optimized for AJAX. The first is actually in how you write your style sheet and is applicable to any XSLT processor. If possible, you should write explicit XSLT templates rather than data-driven ones; by explicit I mean using <xsl:apply-templates /> sparingly and instead opting for <xsl:for-each /> elements to match nodes. It often takes the XSL processor longer to find the templates rather than simply looping explicitly, and this method has the added benefit of slightly reducing the XSLT file size. Certainly the fewer wildcards such as * or // that you use in your XPath queries the faster the transformations will be. Also, using the <xsl:key /> tag and the key() function to create name-value pairs for lookups in complex XML documents can have considerable performance advantages.
The one problem with XSLT is that it has widely varying performance between browsers and in particular between Internet Explorer and any Mozilla-based browser. In IE 6, XSLT is far faster than JavaScript, whereas the opposite is true (to a lesser degree) in Mozilla browsers (see JavaScript/AJAX Benchmarking I).
Given that XSLT in IE is very fast, it is sometimes a good option for doing even mundane operations like formatting numbers using the format-number() function. Furthermore, the recommended method of using XSLT in IE 6 is to use the XSLTemplate object rather than the familiar DOMDocument. The XSLTemplate object compiles and caches the XSLT style sheet, which speeds up future transformations (see MSDN's Increasing Performance by Using the XSLTemplate Object).
Of course if you want your AJAX application to support non-XSLT browsers like Opera, then XSLT might not be the best idea. Sadly even Google's goog-ajaxslt isn't a fast XSLT processor implemented in JavaScript.
JSON
No discussion of AJAX performance would be complete without mentioning JavaScript Object Notation (JSON) since it not only is a very popular alternative to XML but also can be very fast in Mozilla browsers where the JavaScript engine outpaces the XSLT processor considerably.
Data represented in JSON is relatively legible for humans and relatively cheap for JavaScript engines to parse; and it can be instantiated simply by calling the JavaScript eval() method and passing your JSON string as a parameter. Keep in mind that using eval() to do anything tends to be relatively slow. Also, running eval() with JavaScript code that was received from an untrusted source can be a security problem since it can send any JavaScript it wants. To get around this there's JSON JavaScript parser; however, no matter what browser you are using, it is painfully slow. JSON excels in situations where only a few JavaScript objects are being passed from the server to the client and no client-side filtering or sorting needs to be done -- objects can be very quickly and easily instantiated and used within your program context.
DOM and CSS
Interacting with the DOM and changing CSS values can also be time-consuming operations. Both of these require that the browser re-layout and re-render the page. There are also some tags, such as <table>, which tend to be very slow when using any special DOM methods (insertRow() and insertCell() for <table> tags), changing style properties or accessing calculated properties (offsetWidth, offsetLeft, etc.). If you do have to use DOM methods to manipulate nodes such as createElement() and appendChild(), ensure that you do all DOM manipulations offline -- after which use appendChild() or replaceNode() to get the generated nodes into the document. Of course, if you really want to insert (X)HTML into your document quickly, the nonstandard node property innerHTML is the fastest way to go.
Developers are often faced with situations where a group of nodes, say in a list or grid, need the same formatting applied. In those situations one can either loop through all the nodes and set the style properties or class names, or alternatively, access the CSS class directly by using the document.styleSheets[index].rules collection. This, of course, depends greatly on the number of nodes that need to be looped through and the types of style being applied. There are also more unconventional, yet high-performance ways of applying some styles such as background colors. A background color can be simulated by placing an element with a given constant background color behind the element to which you want the background color applied. In both IE 6 and Firefox (Windows) this method is actually faster than setting the background color through CSS.
AJAX Compromise
In AJAX applications, performance is undoubtedly important. Even so, as with any engineering discipline there are compromises to be made. End users will have different operating systems and browsers, applications will have various amounts of code or data to download and process, and there will be different business problems that AJAX can help solve. You need to consider the OS/browser statistics of the target user, and design with performance on those systems in mind. Also, both code and data size have a large effect not only on processing time but also on network latency, which has led to important AJAX design patterns such as pre-fetching of data. The bottom line is that in a commercial environment it is always prudent to let your end users and the business case for your AJAX application direct your choices. Whether you are a single person building an open source AJAX combo box or a small company trying to compete with large AJAX vendors, you need to consider who the end users are and how they use the product.
Writing fast JavaScript isn't always obvious. There are few steadfast rules, and developers need to be vigilant in their performance benchmarking as well as in how they write code. I like to think writing enterprise AJAX applications is a lot like writing assembly code for a real-time system; to make it fast you generally have to step outside of the OOP best practices paradigm and do what works, not what makes your code easy to read and maintain. This flies in the face of some primary virtues of software engineering. Eventually these techniques will mature and become encapsulated in server-side logic and declarative markup where they can be better managed and leveraged. Until then, we'll have to keep on finding new and faster ways of tuning AJAX.
Share your experience in our forums.
(* You must be a member of XML.com to use this feature.)
Comment on this Article
| Titles Only | Titles Only | Newest First |
- Size of XML data on AJAX
2007-05-18 15:03:51 Zombie_Ninja [Reply]
Hi guys,
People talk about using XML on AJAX all the time, I am just wondering, what is the average size of XML data being used for AJAX applications? With and without prefetching?
I am trying to teach some of my students in my tutorial classes and this question has been raised and I thought, wow no one really has benchmarked these kind of things yet.
Regards.
Zombie
- Security issues in JSON
2006-04-12 15:44:13 dbacher987 [Reply]
A number of people talked about XML vs. JSON.
JSON can be used to execute JavaScript insertion attacks against any web client that uses it, unless the server (and only the server) takes appropriate precautions.
Eval performs an unescape. This means that any entities contained in the response are parsed, and replaced with the appropriate character references, which are then processed as JavaScript. To defend against this, any entity reference must be encoded a second time, and wrapped with a manual unencode call.
Many JSON libraries do not correctly perform this task, and (worse) many JSON libraries server-side can't handle doubly encoded requests like this. As a result, it is often necessary to modify the JSON library that you are using to obtain the correct behavior.
On the other hand, XML never causes anything to be executed by its mere presence in a request. If you just blindly replace elements on the document with XML coming from a request, there's a danger in that, but there is no danger in the request itself.
Yes JSON reduces the size of an XML document and eases processing document side, however you absolutely must take precautions if you display any user-entered data using JSON, because you are *EXECUTING* the request to process it, and the request *COULD* contain malicious code.
You can't do the encoding client side because there is no way to tell an entity that is a valid part of the request from an entity that could potentially be hostile.
If you need JSON like functionality and XML is too heavy weight, I would suggest the following, more secure, alternative.
Register the types that you want to create with a JavaScript class. Tell it all the potential types that might appear in the request.
Instead of using JSON, just put a name of a class, a brace, the data, then another brace. Then parse this by hand using the registered functions.
This means that only the registered functions can run in response to the request (so no unintended JavaScript code can run), which cuts off the injection aspect, while reducing the payload even more than JSON does.
- Ajax application on future platforms
2006-03-19 19:38:54 kmurthy [Reply]
If you think, Ajax is interesting wait until next generation browsers are released. The future applications will blow you away.
There are many technologies are emerging (e.g. XAML, MXML, SVG and X3D) which are far more complex than DHTML/HTML to use and build data driven applications (e.g. Games, GIS and real-time simulations), however offer great flexibility and fine-grained capabilities to build superior graphics applications.
The following web site presents a method to create reusable GUI widgets (a higher level reusable building blocks that eliminate the complexity), which can be used to build Ajax applications such as games, GIS or real-time simulations.
http://cbsdf.com/misc_docs/why-gui-api.htm
http://cbsdf.com/misc_docs/gui-api-brief.htm
http://cbsdf.com/technologies/proof-online-GUI-API.htm
See examples:
http://www.cbsdf.com/technologies/demo-links/demo-links.htm
An interesting SVG tutorial to develop an Airplane Widget:
http://www.cbsdf.com/technologies/GUI-Class3.htm
- Presentation Layer on the Server
2006-01-25 02:54:41 IntuiCat [Reply]
Hi All
Our Ajax Catalog Search Engine Demo finely tracks response times:
http://www.abaqueinside.com/IntuiCatAjaxDemoVerif.asp
IntuiCat implements an architecture where server manages presentation and sends ready-made DOM instruction to a universal client JavaScript.
Enjoy !
- Time to End Pathetic Workarounds
2005-12-08 14:36:52 ?XML [Reply]
It is nothing short of scary how slow the internet apps are even in this day and age of modern boxes and technologies when it comes to rendering.
That's with all the optimisations one can come up with..
One message only for the vendors, time to fix it or get a life ;)
- Why AJAX at XML.com?
2005-12-01 07:43:14 Taylor Cowan [Reply]
leaving the acronym aside, I'm puzzled why AJAX is showing up on xml.com. One of the first and most important performance enhancements regarding "AJAX" is to avoid using XML. Responses are being passed as JavaScript, with at most a single XML tag with a cdata.
- Why AJAX at XML.com?
2005-12-01 11:05:49 Bliggy [Reply]
Kendall you said it - JSON is certainly not always faster. It depends greatly on various factors like the amount of data, what client side data processing has to be done, if knowledge of data types is needed, if you are consuming web services and so on. Particularly in IE you can choose either XML or JSON with a slight performance edge going to XML.
I know that for our AJAX DataGrid product JavaScript is far to slow for things like client side sorting so XML + XSL is the only way to go.
- Why AJAX at XML.com?
2005-12-01 10:31:10 Kendall Clark [Reply]
Hmm, well, one of the points Dave made is that JSON is *not* always faster than XML. But the real reason is that XML.com's writers, editors, and audience have always been really interested in the Web. Stuff about the Web that's not necessarily hard-core XML has always been fair game around here.
AJAX is no exception.
That and XML.com announced an editorial re-focus earlier this year which included a greater focus on the Web, web development, what people like to call Web 2.0, and post-XML specification worlds.
Hope that helps.
Kendall Clark
XML.com, Managing Editor
- Why AJAX at XML.com?
