Dom Manipulation - Js Templating vs programmatic jQuery (v28)

Revision 28 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"];
</script>

Test runner

Ready to run.

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

// Fast but too messy imo
ready
Template w/ Direct HTML
var html = '<select><% _.each(values, function(value) { %><option><%= value %></option><% }); %></select >';
$("#testcontainer").append(_.template(html, {
  values: values
}));
ready
jQuery Append w/ Plain Text
var combo = "<select>";
for( var i = 0, blah = values.length; i<blah;i++){
  combo = combo + "<option>"+values[i].replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")+"</option>";
}
combo = combo + "</select>";
$("#testcontainer").append(combo);
ready
Stringed DOM from array
var HTML = ['<select>'];
for (var i = 0, blah = values.length; i < blah; i++) {
HTML.push('<option>', values[i], '</option>');
}
HTML.push('</select>');
$("#testcontainer").append(HTML.join(""));
ready

Revisions

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