knockout (3.0 - 3.1): foreach vs virtual foreach
JavaScript performance comparison
Preparation code
<script src="https://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>
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
<!---->
<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>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
Test | Ops/sec | |
---|---|---|
simple
|
|
pending… |
virtual
|
|
pending… |
simple with templates
|
|
pending… |
virtual like with templates
|
|
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.
- Revision 1: published Andrey
- Revision 2: published
- Revision 3: published
- Revision 4: published Andrey
- Revision 5: published rtet
0 Comments