1

I want to profile an observableArray in KnockoutJS to see how long it's taking to fill and render the observableArray in HTML.

I planned to use an old school method like below. Is the results I'll get from this be accurate? Or is there a better way to do this profiling

JavaScript

    var arr = [],
        itemCount = 200;

    for (var i = 0; i < itemCount; i++) {
        arr.push('item ' + i);
    }

    var t1 = new Date();
    var viewModel = {
        items: ko.observableArray(arr),
        vmName: ko.observable('View Model')
    };

    ko.applyBindings(viewModel);
    var t2 = new Date();


    console.log(t2 - t1); //Shows the time in milliseconds 

HTML

<div data-bind="foreach: items">
    <div data-bind="html: $data"></div>
</div>

Graph I generated from the results

enter image description here

Nipuna
  • 6,846
  • 9
  • 64
  • 87
  • Possible duplicate of http://stackoverflow.com/questions/16520823/knockout-js-is-too-slow-in-filling-observablearray – Dnyanesh Nov 16 '14 at 05:37

1 Answers1

1

As your graph suggests, this is basically the right way to do this. This is because ko.applyBindings is a synchronous call. See here: is ko.applyBindings synchronous or asynchronous?

I would make a small revision, like so, because you're not interested in profiling the time it takes to create observables. However, this time is quite negligible and would only add a tiny, if any, constant to your profiling.

var viewModel = {
    items: ko.observableArray(arr),
    vmName: ko.observable('View Model')
};

var t1 = new Date();
ko.applyBindings(viewModel);
var t2 = new Date();


console.log(t2 - t1); //Shows the time in milliseconds 
Community
  • 1
  • 1
Matthew James Davis
  • 12,134
  • 7
  • 61
  • 90
  • thats a different question. :) if my question was helpful to you, please be sure to upvote and mark it as accepted – Matthew James Davis Nov 16 '14 at 18:19
  • 1
    @Nips on some browsers, `console` has a lot more to offer than just `.log`. Take a look at [`.time`, `timeLine`, `timeStamp` or even `.profile`](https://developer.chrome.com/devtools/docs/console-api#consoletimelabel). – janfoeh Nov 24 '14 at 10:35