admin管理员组

文章数量:1359237

Is it preferable to call the signal multiple times if you're accessing multiple values or would it be more performant to save the current state to a local variable and call that?

submit() {
  this.service.submit({
    price: this.selection().price,
    serialNumber: this.selection().serialNumber,
    quantity: this.selection().quantity
  })
}

vs

submit() {
  let selection = this.selection()
  this.service.submit({
    price: selection.price,
    serialNumber: selection.serialNumber,
    quantity: selection.quantity
  })
}

Is it preferable to call the signal multiple times if you're accessing multiple values or would it be more performant to save the current state to a local variable and call that?

submit() {
  this.service.submit({
    price: this.selection().price,
    serialNumber: this.selection().serialNumber,
    quantity: this.selection().quantity
  })
}

vs

submit() {
  let selection = this.selection()
  this.service.submit({
    price: selection.price,
    serialNumber: selection.serialNumber,
    quantity: selection.quantity
  })
}
Share Improve this question edited Mar 27 at 20:15 jonrsharpe 122k30 gold badges268 silver badges475 bronze badges asked Mar 27 at 14:18 Data DogData Dog 111 silver badge2 bronze badges 1
  • Which is faster? – VLAZ Commented Mar 27 at 14:22
Add a comment  | 

1 Answer 1

Reset to default 0

You are looking at it the wrong way.

If you want the DOM or calculate some other state using some value.

So if you do not want reactivity, go for class properties, if not go for signals.


Just because we call the signal once or thrice, it is not going to increase your performance in a noticeable way.


Even if the signal is having a memory intense computation, the calculation is memoized and unless the input signals of the computation change. The memoized value is only returned, so performance is not compromised.

This is a huge contrast compared to getter which recomputes on each access of the property, so signals are more performant.


The main question is which code snippet has better readability. That is the main question to ask, this will guide you to a satisfactory method mostly.

I would choose the second option because at a glance you can immediately view where the source signal is located which helps grasp the code faster.

submit() {
  let selection = this.selection() // <- oh, the signal is here!
  this.service.submit({
    price: selection.price,
    serialNumber: selection.serialNumber,
    quantity: selection.quantity
  })
}

本文标签: