Performance of observableArray inserts

72 views
Skip to first unread message

Cameron Macintosh

unread,
Jun 29, 2016, 1:32:37 PM6/29/16
to KnockoutJS
I've found a few articles (http://www.knockmeout.net/2012/04/knockoutjs-performance-gotcha.html) and stack overflow posts that point out the fact that doing individual inserts into an observableArray inside a for-loop is less performant than doing push().apply().

Has anyone ever done or found any analysis of how much better this is?  constant?  order of magnitude?

I inherited code that takes the for loop approach, but potentially gets thousands of entries from an ajax call to push into an array.  I want to know at what point should I consider switching over?

I'll post an update if I can come to any strong conclusions.

Ian Yates

unread,
Jun 30, 2016, 7:51:32 AM6/30/16
to KnockoutJS
observableArray is basically an observable that holds an array and has some helper methods exposed to make it more array-like.  One such method is push().

If you have 
var obArray = ko.observableArray()

Then call
obArray.push(item)

That essentially does

var array = obArray();
array.push(item);
obArray(array);

Calling .push(item) many times updates the observable many times, which fires notifcations many times, and so on.

Instead, if you have several items, a common pattern is

var array = obArray();
array.push(item1);
array.push(item2);
...
obArray(array);

to trigger the update one time rather than once for item1, then again for item2, etc.

Using apply, as in
obArray.push.apply(item1, item2)      (or is it [item1, item2] - I'm too used to typescript and spread operators, etc now)

will also just do the .push() call once, which means you just do notification once.

Michael Best

unread,
Jul 20, 2016, 2:18:31 PM7/20/16
to KnockoutJS
obArray.push.apply(obArray, [item1, item2]);

It's the equivalent of obArray.push(item1, item2);

-- Michael
Reply all
Reply to author
Forward
0 new messages