7

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?

Harry Ninh
  • 16,288
  • 5
  • 60
  • 54
TypeScripter
  • 879
  • 2
  • 10
  • 23
  • Try and put a console.log into seeIfItHasBecomeTrue - I suspect it will be called somewhere between 5 and 30 times. If it is a simple function it doesn't matter but if it is more complex it could turn into something measurable. – Esben Skov Pedersen Oct 24 '17 at 05:30
  • anything unclear about [my answer](https://stackoverflow.com/a/46903095/2545680)? – Max Koretskyi Oct 30 '17 at 16:38
  • Apologies for the delay.. And thank you for your answer. Could you please help me with full question? I was looking for , if it is always faster and how fast it is. – TypeScripter Oct 30 '17 at 16:51
  • @TypeScripter, yes, it will be always faster and I explained why in my answer. How faster depends on a particular machine you're running a code on – Max Koretskyi Nov 05 '17 at 07:33

1 Answers1

10

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:

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488