jquery HTML element creation techniques

JavaScript performance comparison

Test case created by lodr

Info

Attemps to dilucidate which option is more suitable for fast DOM manipulation: jQuery string creation, jQuery DOM manipulation methods or Javascript's documentFragment use.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<ul id="test-list">
</ul>
<script>
  var $list = $('#test-list');
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery string creation
$list.empty();
var str = '';
for (var i = 0; i < 100; i++) {
  str += '<li>' + i + '</li>';
}
$list.html(str);
pending…
jQuery DOM manipulation methods
$list.empty();
for (var i = 0; i < 100; i++) {
  var $li = $('<li>').detach().html(i);
  $list.append($li);
}
pending…
Javascript's documentFragment
$list.empty();
var container = document.createDocumentFragment();
for (var i = 0; i < 100; i++) {
  var li = document.createElement('li');
  li.innerHTML = i;
  container.appendChild(li);
}
$list.html(container);
pending…
Javascript's document manipulation
var container = document.getElementById('test-list');
container.innerHTML = '';
for (var i = 0; i < 100; i++) {
  var li = document.createElement('li');
  li.innerHTML = i;
  li.setAttribute('title', 'Element number ' + i);
  li.setAttribute('class', 'list-item');
  container.appendChild(li);
}
pending…
jQuery DOM manipulation methods (fragment/DOM hybrid)
$list.empty();
var container = document.createDocumentFragment();
for (var i = 0; i < 100; i++) {
  var $li = $('<li>').detach().html(i);
  container.appendChild($li[0]);
}
$list.html(container);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment