named vs inline templates in Knockout.js

JavaScript performance comparison

Revision 8 of this test case created by Michael Best and last updated

Preparation code

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

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

<script id="templateInline" type="text/html">
    <table><tbody data-bind="template: { foreach: rows }">
        <tr data-bind="template: { foreach: cells }">
            <td>xxx</td>
        </tr>
    </tbody></table>
</script>

<script id="templateMemory" type="text/html">
    <table><tbody data-bind="template: { foreach: rows, id: 'templateMRow' }">
        <tr data-bind="template: { foreach: cells, id: 'templateMCell' }">
            <td>xxx</td>
        </tr>
    </tbody></table>
</script>

<script id="templateNamed" type="text/html">
    <table><tbody data-bind="template: { foreach: rows, name: 'templateRow' }"></tbody></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>xxx</td>
</script>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://raw.github.com/mbest/knockout/playground/build/output/knockout-latest.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]);
viewModel.tmplName('templateNamed');
viewModel.tmplName('templateInline');
viewModel.tmplName('templateMemory');
viewModel.tmplName('templateDummy');
</script>
      
<script>
Benchmark.prototype.setup = function() {
  viewModel.tmplName('templateDummy');

};
</script>

Preparation code output

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

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
template named
viewModel.tmplName('templateNamed');
viewModel.tmplName.notifySubscribers();
pending…
template inline
viewModel.tmplName('templateInline');
viewModel.tmplName.notifySubscribers();
pending…

Compare results of other browsers

Revisions

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

0 Comments