Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: $(template) vs .clone()

Lets say we have a complex string template (maybe a div containing lots of other tags..) and we need to add this HTML node multiple times to our existing document.

Will it be faster to create the HTML nodes from the template each time

var $html = $(template); // 1st run
var $html = $(template); // 2st run
...

or to only create them once and then clone them:

var $template = $(template); // init
var $html = $template.clone() // 1st run
var $html = $template.clone() // 2st run
...
like image 207
lrsjng Avatar asked Oct 20 '12 14:10

lrsjng


1 Answers

Using a template seems to be consistently faster for short templates than a clone on all browsers tested so far except Opera (one test case, equal performance). Thank you all for the test cases.

http://jsperf.com/clone-versus-template

update:

this is the test with a long template and template built with jQuery:

http://jsperf.com/clone-versus-template/4

this last test shows that the clone method far outperforms the template method on Chrome, Firefox and Opera alike, but they are equal in IE9

like image 165
John Dvorak Avatar answered Oct 06 '22 10:10

John Dvorak