2

Using knockout.js components I'm wondering if performance get affected when passing multiple viewmodels to a component instead of just a single one.

Having the following:

function masterViewModel(){
    this.demo = new demoViewModel().init();
    this.demo2 = new demo2ViewModel().init();
    this.demo3 = new demo3ViewModel().init();
    this.demo4 = new demo4ViewModel().init();
    this.demo5 = new demo5ViewModel().init();
    this.demo6 = new demo6ViewModel().init();
}

var mm = new masterViewModel();
ko.applyBindings(mm, $(':root').get(0));

I was thinking of passing the whole masterViewModel variable to my component in order to be able to access all viewmodels from it:

ko.components.register(element, {
    viewModel: { instance: mm },
    template: { require: 'text!views/myComponent.html' },
});

Would performance get affected in a bad way if I do that instead of just passing a single viewmodel?

ko.components.register(element, {
    viewModel: { instance: mm.demo3 },
    template: { require: 'text!views/myComponent.html' },
});
Alvaro
  • 40,778
  • 30
  • 164
  • 336

1 Answers1

2

Will there be any noticeable performance difference between register option 1 and 2? No. With just the code you've presented, the two options are nearly equivalent, except for one instance of the . operator. Negligable.

Knockout will not AFAIK walk the entire view model object graph to take action (e.g. subscribe to observable changes), it just keeps a reference to the view model instance.

Apart from that very direct answer to the question: performance is context dependent. If you have doubts which option is faster: race your horses.

Jeroen
  • 60,696
  • 40
  • 206
  • 339
  • I'm not worried about the operator itself, but about how Knockout.js deals with the viewModels when passing them to a component. As 7 big viewmodels are much more logic than just 1. But it seems you've replied that as well. – Alvaro Jun 02 '16 at 14:09