3

From this post:

I would first suggest that you optimize your dependentObservable (a.k.a. computed). When you read any observable, Knockout registers a dependency to it in Dependency Manager...

I can see in your pseudo-code that you are accessing this.ParentList() in the while loop. It means registerDependency will be called 3000 times and the dependencies array will be scanned 3000 times, which is bad for IE (since it has no built-in Array.indexOf method).

So my number one suggestion would be: Read all observables before loops.

With this good advice in mind, here's my question:

Is it bad form to iterate through observable arrays with ko utility methods (like the following)? [assume that this.mySelectListItems() is an observableArray]:

self.selectedValuesCount = ko.computed(function () {
    var total = 0;
    ko.utils.arrayForEach(this.mySelectListItems(), function (item) {
        if (item.selected() === true) {
            total += 1;
        }
    });
    return total;
}, self);

In other words, is there anything to be gained by doing the following?

self.selectedValuesCount = ko.computed(function () {
    var total = 0;
    var myArray = this.mySelectListItems();
    ko.utils.arrayForEach(myArray, function (item) {
        if (item.selected() === true) {
            total += 1;
        }
    });
    return total;
}, self);
Community
  • 1
  • 1
Jim G.
  • 15,141
  • 22
  • 103
  • 166

2 Answers2

4

No, those bits of code are perfectly equal.

You would only gain a performance boost if you'd retrieve the value of the same observable again and again in the callback that you hand over to arrayForEach - but in this case, the value of the observable array gets retrieved just once, so there is no point why you would want to put that array in an extra variable.

Niko
  • 26,516
  • 9
  • 93
  • 110
2

Are you actually experiencing a performance hit? Unwrapping observable arrays for a loop makes sense for very large data sets, but if you've only got a dozen or so you should be fine. Also, if you're making changes to the observable array itself such as sorting or removing elements, unwrapping it first would prevent any data-bindings/subscriptions from updating as you would just be modifying a regular array.

Remember, premature optimization is the root of all evil.

daedalus28
  • 1,637
  • 1
  • 12
  • 24