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

Viewed 110
@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 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.

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.

Related