[Vuejs]-Is calling computed property from inside Vue method multiple times affecting the performance?

0đź‘Ť

âś…

First of all I’d like to mention that whatever method you end up using, it’s unlikely to yield a significant performance improvement. If performance is your primary concern, then you should profile your webpage to determine which method works best. Most of the time I would preference code readability/maintainability over performance.

1. No computed properties, declare divHeight in every method separately.

methods: {
  firstMethod() {
    var divHeight = this.$refs.divRef.clientHeight;
    ...
  },

  secondMethod() {
    var divHeight = this.$refs.divRef.clientHeight;
    ...
  }
}

This is preferable if the div’s height can change, so you do want to fetch the correct height each time the methods are called in case the height was changed.

2. Make divHeight computed property, declare it anyway as a variable inside a method.

computed: {
  divHeight() {
    return this.$refs.divRef.clientHeight;
  }
},

methods: {
  firstMethod() {
    var divHeight = this.divHeight;
    ...
  },

  secondMethod() {
    var divHeight = this.divHeight;
    ...
  }
}

divHeight will be calculated once only, the first time the property is accessed. If the div’s height changes then divHeight will not be recalculated. This solution is not suitable for this situation since computed properties are typically used when that property relies on other observable data properties of that component (this.$refs.divRef.clientHeight is not observable by Vue).

3. Make divHeight computed property, use this.divHeight multiple times inside a method.

computed: {
  divHeight() {
    return this.$refs.divRef.clientHeight;
  }
},

methods: {
  firstMethod() {
    this.divHeight/this.divWidth = something;
    this.divHeight... other operations.
  },

  secondMethod() {
    this.divHeight/this.divWidth = something;
    this.divHeight... other operations.
  }
}

This is the same as #2 except you’re accessing this.divHeight multiple times in each method. The only “improvement” this has over #2 is avoiding the property access, which is negligible; but if you’re using this.divHeight many times in a method then perhaps #2 is better to avoid having this. everywhere.


I would suggest this instead:

methods: {
  divHeight() {
    return this.$refs.divRef.clientHeight;
  },

  firstMethod() {
    var divHeight = this.divHeight();
    ...
  },

  secondMethod() {
    var divHeight = this.divHeight();
    ...
  }
}

This is basically the same as #1 except it’s a bit shorter because you don’t have to type this.$refs.divRef.clientHeight everywhere.

Leave a comment