In this post I'm going to show you how to implement a simple performance test with jQuery. We're going to demonstrate that the html()
method is considerably faster than appendTo()
. To accomplish this, we'll calculate the number of milliseconds required for inserting 1,000 elements into the DOM by using either methods. We first need a basic benchmark object to calculate these time differences:
var BenchMark = new function() { this.startTest = function() { var ts = new Date(); return ts.getMilliseconds(); }; this.endTest = function() { var ts = new Date(); return ts.getMilliseconds(); }; }();
We use the getMilliseconds()
method of the Date
object to get two different timestamps, one at the beginning of the test and the other at the end of it. Then we'll subtract the end value from the start value in order to know the number of milliseconds required by the browser to complete its task. Here's how we can actually do:
$(function() { $('#run1').click(function(event) { $('#test').empty(); var start = BenchMark.startTest(); var i; for(i = 0; i < 1000; i += 1) { $('<div/>').text(i).appendTo('#test'); } var end = BenchMark.endTest(); $('#results').html(end - start + ' milliseconds'); event.preventDefault(); }); $('#run2').click(function(event) { var start = BenchMark.startTest(); var i, html = ''; for(i = 0; i < 1000; i +=1) { html += '<div>' + i + '</div>'; } $('#test').html(html); var end = BenchMark.endTest(); $('#results').html(end - start + ' milliseconds'); event.preventDefault(); }); });
Obviously results vary from browser to browser. So, what's the fastest browser? Let me guess: is it Chrome? wink