Considerations when updating the DOM to display realtime data

12 Feb 2012

When data is being delivered to web applications the chances are that you'll be displaying that data within the user interface (UI). In order to do this you need to find the element in the Document Object Model (DOM) and then update it. Whilst the performance of web browsers is improving all the time DOM manipulation can still be costly (use up time and resources) if you are pushing through a lot of data so it's worth keeping the interaction with the DOM to a minimum. You should also consider how you access the DOM. Should you use a utility/library function or should you use native browser methods?

To demonstrate this, and show the considerations I've written a few small helper functions which can be called a number of times from tests and for each test I'll time how long it takes to update the DOM a certain number of times.

For many web developers a script tag referencing in the jQuery library is one of the first elements to be added to any web page - it's even in some web framework templates by default. So, a good first test is to time how long it takes for jQuery to update an element a number of times.

Now that we've defined one way of updating the DOM let's add a way of caching a reference to the jQuery object that we create with the jQuery(selector) call. So, instead of having to make that call each time we can just access the object from a cache. This means that a new jQuery object doesn't need to be created for every update.

jQuery uses CSS selectors to find elements so rather than going directly to single elements using id attributes let's also define a test that uses a nested selector: div.middle div.bottom p.update-me.

Finally, as a comparison let's define functions which update the DOM by directly using the native document.getElementById and document.querySelector native browser functions, and both of these again using the caching technique we used earlier.

If we execute each of these methods so that they are called 500 times to update the DOM and repeat that 10 times we see results as shown in the following graph.

Time in milliseconds (y-axis) it takes to update an element within the DOM (+1) times. The test is ran a number of times (x-axis)

And if we take each of the results and average them out we see the following:

The chart above shows the average time it takes to find the element and update the DOM using different techniques