Archive for the ‘performance’ Tag

Kockout performance tip #1

After reading two posts(#1 and #2) from one of the Knockout project members, Ryan Niemeyer, I did some performance testing on my application and found an improvement:

The Problem: Rendering and processing elements that are not visible

<table data-bind="foreach: Items">
	<tr>
		<td data-bind="text: Name"></td>
		<td>
			<input type="button" data-bind="click: edit" value="Edit"/>
		</td>
	</tr>
	<tr data-bind="visible: IsEditing()">
		<td colspan="4" style="background: white;">
			<table data-bind="foreach: SubItems">
				<tr>
					<td data-bind="text: Name"></td>
				</tr>
			</table>
		</td>
	</tr>
</table>

This code creates a table with two rows for each Master Item (in the Items list):

  • A row with the Item name and an Edit button
  • Another row with an inner table with the list of the child items (in the SubItems list).

The thing is, the second row only appears when the user clicks on the Edit button (callind the Item.edit method, witch in turn changes the IsEditing to true). With the code above, Knockout was processing all bindings (even the ones from the SubItems). Depending on the amount of SubItems or bindings, the ko.applyBindings method can taking quite some time.

The Solution: Using an If binding to control witch elements are rendered and processed

<table data-bind="foreach: Items">
	<tr>
		<td data-bind="text: Name"></td>
		<td>
			<input type="button" data-bind="click: edit" value="Edit"/>
		</td>
	</tr>
	<tr data-bind="if: IsEditing()">
		<td colspan="4" style="background: white;">
			<table data-bind="foreach: SubItems">
				<tr>
					<td data-bind="text: Name"></td>
				</tr>
			</table>
		</td>
	</tr>
</table>

Changing the visible binding to the if binding, made Knockout only process and render the details row (with all the SubItems) when the Master Item was being edited. In my page (a lot more complex than the example above and with a lot of data), it made the ko.applyBindings execution 2 seconds faster.

Advertisements