named vs inline templates in Knockout.js v3.0 (v18)

Revision 18 of this benchmark created on


Preparation HTML

<div id="main" data-bind="template: tmplName"></div>

<script id="templateDummy" type="text/html"></script>

<script id="templateInline" type="text/html">
    <table data-bind="template: { foreach: rows }">
        <tr data-bind="template: { foreach: cells }">
            <td data-bind="text: 'Cell ' + id()"></td>
        </tr>
    </table>
</script>

<script id="templateMemory" type="text/html">
    <table data-bind="template: { foreach: rows, id: 'templateRow' }">
        <tr data-bind="template: { foreach: cells, id: 'templateCell' }">
            <td data-bind="text: 'Cell ' + id()"></td>
        </tr>
    </table>
</script>

<script id="templateNamed" type="text/html">
    <table data-bind="template: { foreach: rows, name: 'templateRow' }"></table>
</script>
<script id="templateRow" type="text/html">
    <tr data-bind="template: { foreach: cells, name: 'templateCell' }"></tr>
</script>
<script id="templateCell" type="text/html">
     <td data-bind="text: 'Cell ' + id()"></td>
</script>


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

<script>
function Cell(id) {
    this.id = ko.observable(id);   
}
function Row(id) {
    this.id = ko.observable(id);
    this.cells = ko.observableArray();
}

var viewModel = {
    tmplName: ko.observable('templateDummy'),
    rows: ko.observableArray()
};

for (var i = 0; i < 5; i++) {
    var row = new Row(i);
    
    for (var j = 0; j < 5; j++) {
        row.cells.push(new Cell(i + " - " + j));
    }
    viewModel.rows.push(row);
}
var main = $("#main");
ko.applyBindings(viewModel, main[0]);
</script>

Setup

viewModel.tmplName('templateDummy');

Test runner

Ready to run.

Testing in
TestOps/sec
templateNamed
viewModel.tmplName('templateNamed');
viewModel.tmplName.notifySubscribers();
ready
templateInline
viewModel.tmplName('templateInline');
viewModel.tmplName.notifySubscribers();
ready
cache node
 (function() {
        var old = ko.utils.parseHtmlFragment;
        var nodes = {};
        ko.utils.parseHtmlFragment = function(html) {
            var digest = hash(html.length);
            if(nodes[digest]) {
                return [nodes[digest].cloneNode(true)];
            }       
            var node = old(html);
            // 
            nodes[digest] = node[0].cloneNode(true);
            return node; 
        };      
    }());
viewModel.tmplName('templateInline');
viewModel.tmplName.notifySubscribers();
ready

Revisions

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