A myth about jQuery performance versus DOM performance: creating elements

There are some common myths and beliefs regarding the overall performance of jQuery when compared to the traditional DOM methods that need to be further investigated. Let's say that we have to create a large number of elements and insert them into the page. Which approach is faster?

The best thing to do is to test by ourselves:


$(function() {
	var time = document.querySelector('#time'),
		output = document.querySelector('#output'),
		max = 1000;
	$('#dom').one('click', function() {
		$('#output').empty();
		var startTime = +new Date;
		for(var i = 0; i < max; ++i) {
			if(i == (max - 1)) {
				var endTime = +new Date;
				$(time).text((endTime - startTime) + ' ms');
			}
			var e = document.createElement('div');
			var t = document.createTextNode('Test');
			e.appendChild(t);
			output.appendChild(e);
		}
	});
	$('#jquery').one('click', function() {
		$('#output').empty();
		var startTime = +new Date;
		for(var i = 0; i < max; ++i) {
			if(i == (max - 1)) {
				var endTime = +new Date;
				$(time).text((endTime - startTime) + ' ms');
			}
			var e = $('<div/>');
			e.text('Test').appendTo('#output');
		}
	});
});

And the winner is... well, if we think carefully about the DOM core methods and jQuery methods, we'll surely find the answer. Remember that DOM methods are implemented using the browser-level code (usually C or C++), so it's pretty easy to guess our test's results.

[view-example url="http://codepen.io/gabrieleromanato/pen/zDwgo"]
Back to top