$('<div class='foobar' ...>') vs $('<div>',{'class':'foobar'...})

JavaScript performance comparison

Test case created by Yutaka Yamaguchi

Info

There are 2 ways to create new DOM with jQuery like the following.

1) $('<div class="foobar">foobar</div>') 2) $('<div>',{'class':'foobar','text':'foobar'})

The former is using innerHTML, and the latter is using createElement and add attributes later.

http://api.jquery.com/jQuery/#jQuery2

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
innerHtml
$('<div class="foobar">foobar</div>')
pending…
createElement and add attributes
$('<div>',{'class':'foobar','text':'foobar'})
pending…
createElement and add attributes with chain
$('<div>').addClass('foobar').text('foobar')
pending…
pure Javascript DOM operation
var div = document.createElement('div');
div.setAttribute('class','foobar');
'textContent' in div ? div.textContent = 'foobar' : div.appendChild(document.createTextNode('foobar'));
pending…
test4 + wrap in a Jquery obj
var div = document.createElement('div');
div.setAttribute('class','foobar');
'textContent' in div ? div.textContent = 'foobar' : div.appendChild(document.createTextNode('foobar'));
var $div = $(div);
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment