Dom Manipulation - Js Templating vs programmatic jQuery (v2)

Revision 2 of this benchmark created on


Description

What is faster, generating elements on the fly using jQuery appends and generator or using javascript templates.

Preparation HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.1.7/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<!-- The Javascript template - using underscore.js -->
<script type="text/template" id="combo_template">
    <select> 
    <% _.each(values, function(value) { %>
        <option><%= value %></option>
    <% }); %>
    </select >
</script>

<div id="testcontainer" style="display: none;"></div>
<script>
  $("#testcontainer").empty();
  var values = ["SOMETHING", "THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS","THOMAS"],
      tpl = _.template($("#combo_template").text()),
      combo = $("<select/>"),
      option = $("<option/>");
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Javascript Templates
$("#testcontainer").append(tpl({ values: values }));
ready
jQuery Append
var c = combo.clone();
for( var i = 0, l = values.length; i < l; i++){
  c.append(option.clone().text(values[i]));
}
$("#testcontainer").append(c);
ready
Stringed Dom
var HTML = '<select>';
for( var i = 0, l = values.length; i< l; i++){
HTML += '<option>' + values[i] + '</option>';
}
HTML += '</select>';
$("#testcontainer").append(HTML);

// Fast but too messy imo
ready

Revisions

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