Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are simple get methods costly when using them in the view?

@Component({
  template: `Hello {{user.getName()}}``
})
class UserProfile {
  user: User = new User();
}

Let's say that user has all fields private and the only way to access them is by calling methods. We all know that Angular calls change detection rather often but I'm curious whether such simple method like:

getName(): string {
  return this.name;
}

costs something? If change detection triggers a lot of times then all those methods calls are being added to the stack. What's your opinion?

like image 736
elzoy Avatar asked Dec 11 '25 02:12

elzoy


1 Answers

Using method or getter in view is more performance heavy. It is good practice to store data in variables, because for view binding expensive calculation should be avoided because the method or getter can be called very often because of change detection. So it's better to store the result in a field and bind to the field instead.

Binding to fields is more efficient, then using getters and methods in binding.

like image 155
StepUp Avatar answered Dec 14 '25 01:12

StepUp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!