read

IMPORTANT UPDATE: One-Time Bindings have a huge improvement on performance when applied correctly. See updated results below.

How well does track by improve ng-repeat loop speed? What is the impact of one-time bindings on performance? I made a quick test, and found the results surprising.

Recently I wrote an article about performance testing. Using the same method from the article, we have the tools to test performance improvements in Angular 1.

I compared:

  • One-time binding vs. with normal binding
    • {{ name }}
    • {{ ::name }}
  • Tracked and un-tracked repeaters
    • ng-repeat="r in app.rows"
    • ng-repeat="r in app.rows track by $index"

As well as combinations of the two. The code in question consists of a nested loop as seen below.

    <tr ng-repeat="r in app.rows">
      <td ng-repeat="name in r.names"
          ng-class="{'waldo': app.isWaldo(name)}">
            {{name}}
      </td>
    </tr> 

For more information about the method, refer to the performance testing article or the Github repo. I encourage you to run the tests for yourself, it's much easier than you might think.

I've posted the results below:

Generate Rows: Script Times

time (ms) / # of items

`track by`, `{{ name }}`   `track by`, `{{ ::name }}`   `{{ name }}`   `{{ ::name }}` `{{ ::app.rows, ::r.names, ::name }}`



As expected, track by added significant performance improvements. One time bindings only paid off when placed on the arrays being looped over.

Changes: Script Time

time (ms) / # of items

`track by`, `{{ name }}`   `track by`, `{{ ::name }}`   `{{ name }}`   `{{ ::name }}` `{{ ::app.rows, ::r.names, ::name }}`



In order to get one-time bindings to work you need to apply them to the rows as well. Below is the most optimized code:

     <tr ng-repeat="r in ::app.rows track by $index">
      <td ng-repeat="name in ::r.names track by $index"
          ng-class="{'waldo': app.isWaldo(name)}">
           {{::name}}
      </td>
    </tr>

Thank you to Vincent Eulonge for helping me correct the initial incorrect conclusion. I hadn't used one-time bindings on the values being looped over, only the final target value. Above is the correct way to apply one-time bindings.

Conclusion

Performance testing can provide a lot of insights into what works and what doesn't. When implemented correctly, track by & one-time bindings are an easy ways to improve performance in Angular 1.

Blog Logo

Shawn McKay

Published

Image

ShMcK

JavaScript Web Dev

Back Home