Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Performance: Is it better to bind with a data member than a function?

I wanted to have some idea about whether binding to data member is better in performance vs binding to a function?

e.g. which of the below statement will have better performance?

1)

<myComp *ngIf="isThisTrue"></mycomp>

where isThisTrue is being set via a method

checkIfTrue(data){
       this.isThisTrue = data;
}

where this checkfTrue() is being called on receiving an event from an observable.

or

2)

<mycomp *ngIf="seeIfItHasBecomeTrue()"></mycomp>

where seeIfItHasBecomeTrue checks to see whether this.isTrue has become true or not.

I clearly feel that binding to data member should be faster, but I am not sure if this will always be faster? or if there are some gray areas? Also, if it is faster then how much?

like image 336
TypeScripter Avatar asked Oct 24 '17 05:10

TypeScripter


1 Answers

If you use the approach *ngIf="isThisTrue" the compiler will generate the following updateRenderer function:

function (_ck, _v) {
    var _co = _v.component;
    var currVal_1 = _co.isThisTrue;   <--- simple member access
    _ck(_v, 5, 0, currVal_1);
}

If you use the second approach *ngIf="seeIfItHasBecomeTrue()", the function will look like this:

function(_ck,_v) {
    var _co = _v.component;
    var currVal_1 = _co.seeIfItHasBecomeTrue();   <--- function call
    _ck(_v,5,0,currVal_1);
}

And the function call is more performance heavy than simple member access.

To learn more about updateRenderer function read:

  • The mechanics of DOM updates in Angular
like image 77
Max Koretskyi Avatar answered Nov 05 '22 07:11

Max Koretskyi