Performance problems using Knockout observableArray

Knockout is a UI framework for building single page apps. In Knockout, observable and observableArray are two basic functions. Observable enables two-way binding between the UI and the data in View Model.

ObservableArray stores a collection of View Models. When a View Model is added or removed from the array, the bindings are re-evaluated. And the UI is re-rendered. Most of the array operations are supported. For example, the push function adds elements to the collection.

var collection = ko.observableArray();
for(var index=0; index < sourceCollection.length; index++) {
    var item = sourceCollection[index];
    var model = new ViewModel();
    // copy item in to model
    collection.push(model);
}

There are performance problems with the above code. For each new iteration, the UI is recomputed. And the UI renders again. Repetitive push operation is computation intensive and leads to performance problems.

Recently, I was working with a collection of 1000 elements. Pushing items, one by one, took about seven seconds.

There is a work-around. Insert all the items into an array. Finally, set the array to the observableArray as a final step.

var collection = ko.observableArray();
var tmpArray = new Array();
for(var index=0; index < sourceCollection.length; index++) {
    var item = sourceCollection[index];
    var model = new ViewModel();
    // copy item in to model
    tmpArray.push(model);
}
collection(tmpArray);

With the same 1000 item array, the above operation completed in 400 ms.

Performance problems in Knockout have a common theme. There are unnecessary re-renders.

Update (September 2017): There is a CodeMentor article that does a performance comparison between React, Angular and Knockout. The test inserts 1000 items into an array. And the benchmark test took 400 ms to run.

Related Posts

One thought on “Performance problems using Knockout observableArray

  1. Hi,

    Just wondering if there is performance issue in “collection([])” in your case?

    My current performance issue is not in the adding to the collection, instead, is in cleaning the collection by using “collection([])”, it takes ages for about 1200 items.

Leave a Reply

Your email address will not be published.