knockout (3.0 - 3.1): foreach vs virtual foreach

JavaScript performance comparison

Revision 2 of this test case created

Info

Need to know, if foreach (and, maybe, template with foreach) is faster then using virtual elements

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<!--<script src="http://knockoutjs.com/downloads/knockout-3.1.0.js"></script>-->
 <script src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>

<script type="text/html" id="template1">
<div><div data-bind="text: $data.Name() + 'template1'"></div></div>
</script>
<script type="text/html" id="template2">
<div><div data-bind="text: $data.Name() + 'template2'"></div></div>
</script>


<div id="simpleContainerWithTemplate" data-bind="foreach: items">
<div data-bind="template: { name: templateName, foreach: items }"></div>
</div>

<div id="virtualContainerWithTemplate">
<!-- ko: foreach: items -->

<!-- ko: if: $index%2 == 0 -->
<div><div data-bind="text: $data.Name"></div></div>
<!-- /ko -->

<!-- ko: if: $index%2 != 0 -->
<div><div data-bind="text: $data.Name"></div></div>
<!-- /ko -->

<!-- /ko -->
</div>



<div id="simpleContainer" data-bind="foreach: items">
<div data-bind="text: $data.Name"></div>
</div>

<div id="virtualContainer">
<!-- ko: foreach: items -->
<div data-bind="text: $data.Name"></div>
<!-- /ko -->
</div>


<script type="text/javascript">

var Item = function(data) {
  var self = this;
  self.Name = ko.observable(data.Name);
};


function TestModel() {
  var self = this;

self.items = ko.observableArray();

self.templateName = function (i) {

if (i.Name()%2 == 0)
return 'template1';

return 'template2';
};
(function () {
 self.update = function() {

        var temp = [];
        for (var i = 0; i < 100; i++) {
                temp.push(new Item({ Name: "name_" + i}));
        }
        self.items(temp);
temp.length = 0;
};
});
};


</script>
 

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
simple
var mod = new TestModel();
ko.cleanNode($('#simpleContainer')[0]);
ko.applyBindings(mod, $('#simpleContainer')[0]);
pending…
virtual
var mod = new TestModel();
ko.cleanNode($('#virtualContainer')[0]);
ko.applyBindings(mod, $('#virtualContainer')[0]);
pending…
simple with templates
var mod = new TestModel();
ko.cleanNode($('#simpleContainerWithTemplate')[0]);
ko.applyBindings(mod, $('#simpleContainerWithTemplate')[0]);
pending…
virtual like with templates
var mod = new TestModel();;
ko.cleanNode($('#virtualContainerWithTemplate')[0]);
ko.applyBindings(mod, $('#virtualContainerWithTemplate')[0]);
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. Here’s a list of current revisions for this page:

0 comments

Add a comment