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
...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With