Search code examples
angularjsangularjs-scope

Maximise effectiveness of one-time bindings


I'm currently working on the performance of an angularJS application, and was wondering if there is any difference in performance between these two examples:

http://plnkr.co/edit/T5aHybkkCoF5MDzXX2Kk?p=preview

http://plnkr.co/edit/sX2ffPPOQTyFbb70elwp?p=preview

The difference is that in the first example, in the file 'testdirective.html' the ng-if boolean is not bound in a one time expression. However, it is already bound as a one-time binding in the 'index.html'.

<div ng-if="enabled"> 
        vs
<div ng-if="::enabled">

Is using a one-time expression in the directive as well as in the index file better for the performance?

Thanks!


Solution

  • Yes, there will be a performance difference (although negligible in this case).

    The directive doesn't take into account if the value passed to it was one-time bound or not, so if the directive's template doesn't use a one-time binding it will register a new watcher.

    The cost of running this watcher during the digest cycle will bascially be the difference in performance in the two examples.

    An extra note on your example that doesn't really touch the question is that the following two cases will behave the same:

    <testdirective enabled="::true"></testdirective> 
    

    And

    <testdirective enabled="true"></testdirective> 
    

    In the second case true will be treated as a constant that cannot change and the registered watcher will be removed, just like with a one-time binding.