在vue3中,computed计算属性性能

eqqqjvef  于 2022-11-17  发布在  Vue.js
关注(0)|答案(1)|浏览(269)

在下面的例子中,使用vue3的computed属性,我们应该把“computed”放在最外层,还是只对数据做“computed”?哪一个性能更好?

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'}]},
]
bfrts1fy

bfrts1fy1#

第二种方法的性能应该更高。
让我们假设cpuData中发生了一些变化
1.在第一种情况下,它将触发整个computed属性重新计算,这意味着disData.mapmemoryData.maptestData.map将被再次执行,即使那里什么都没有改变。
1.在第二种情况下,只会重新计算第一个计算的属性(包含cpuData.map),移除这些不必要的额外计算。
此外,还有一些其他原因选择第二种方法,如Vue风格指南中所述

相关问题