I am a fan of Knockout. I recommend using Knockout over jQuery for any non-trivial UI. In Knockout, observable() and observableArray() are two basic objects. observable() enables two-way binding between the UI and the javascript View Model. observableArray() provides array functionality to an observable(). observableArray() can be used to store a collection of View Models.

The natural way to add elements to an observableArray is using the push function:

The above pattern is very common in Knockout applications. From a source collection, we are iterating over each source element, and creating the corresponding View model for it. We then push the View model into the observableArray.

Though the above works fine, it induces performance problems. For each new push into the observableArray(), the UI is recomputed, the computed observables() based on this observableArray() are recomputed, and so on. In short, the simple push operation is computation intensive and leads to performance problems.

In my scenario, a push of 1000 elements took about 7 seconds. By using the below code, insertion into observableArray() happened within 400 milli-seconds.

By inserting elements into a temporary array, and later assigning the array to the observableArray(), the Knockout.js performance problem is resolved.

Performance problems using Knockout observableArray
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *