3
votes
@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?

2
Though I dont know the best way, but yes it is costly, try console in that method and it will keep logging again and again. - Pardeep Jain
I had read a great article yesterday talking about that, you can have a quick look: blog.appverse.io/… - Eudz
Angular needs to check if the value has changed to update DOM accordingly. When you use a method, angular needs to call it during every cycle to check if the value has been updated. So yes, you should avoid using method in interpolation - Florian

2 Answers

1
votes

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.

0
votes

If you just return a value from function it's not cost much. You also can create getter for better syntax:

get userName() {
 return this.user.getName();
}

but if you make some calculations in the method it can decrease render performance, but you can use pure Pipe behaviour (pure pipes implemets memorization pattern) for optimization (you can use already created ngx-pipe-function.