Home > front end >  In vue3, computed computes the property performance
In vue3, computed computes the property performance

Time:11-06

In the following example, using the computed property of vue3, should we put "computed" in the outermost layer or do "computed" on the data alone? Which performs better?

const arr = computed(()=>[
  {options:cpuData.map((item)=>({...item,name:'tom'}))},
  {options:disData.map((item)=>({...item,name:'jerry'}))},
  {options:memoryData.map((item)=>({...item,name:'oh'}))},
  {options:testData.map((item)=>({...item,name:'test'}))},
  {options:[{name:'test'},{name:'test2'}]},
  {options:[{name:'test'},{name:'test2'}]},
  {options:[{name:'test'},{name:'test2'}]},
  {options:[{name:'test'},{name:'test2'}]},
])

const arr = [
  {options:computed(()=>cpuData.map((item)=>({...item,name:'tom'}))),
  {options:computed(()=>disData.map((item)=>({...item,name:'tom'}))),
  {options:computed(()=>memoryData.map((item)=>({...item,name:'tom'}))),
  {options:computed(()=>testData.map((item)=>({...item,name:'tom'}))),
  {options:[{name:'test'},{name:'test2'}]},
  {options:[{name:'test'},{name:'test2'}]},
  {options:[{name:'test'},{name:'test2'}]},
  {options:[{name:'test'},{name:'test2'}]},
]


CodePudding user response:

The second approach should be more performant.

Let's assume something has changed in the cpuData

  1. In the first case, it will trigger the whole computed property to recompute. Which means disData.map, memoryData.map and testData.map will be executed again, even though nothing had changed there.
  2. It the second case, only the first computed property (containing cpuData.map) will be recomputed, removing these unnecessary additional calculations.

Also there are some other reasons to pick the second approach, described in Vue style guide

  • Related