定义计算属性中的变量对Vue组件的性能有任何影响吗?
背景:我构建了一个表组件,它一般从传递的数据生成HTML表,并且每个列都有不同的过滤器、整个表的筛选器、排序键等等,所以我在计算属性中定义了许多局部变量。
想象一下拥有一个对象数组:
let data = [
{ id: "y", a: 1, b: 2, c: 3 },
{ id: "z", a: 11, b: 22, c: 33 }
]Vue组件使用..which来显示数据:
<template>
<div>
<input type="text" v-model="filterKey" />
</div>
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr v-for="item in filteredData" :key="item.id">
<td v-for="(value, key) in item" :key="key">
{{ value }}
</td>
</tr>
</tbody>
</table>
</template>通过输入过滤数据:
<script>
export default {
props: {
passedData: Array,
},
data() {
return {
filterKey: null,
};
},
computed: {
filteredData() {
// defining local scope variables
let data = this.passedData;
let filterKey = this.filterKey;
data = data.filter((e) => {
// filter by filterKey or this.filterKey
});
return data;
},
},
};
</script>我的问题提到了let data = ..和let filterKey = ..,因为filteredData()是由filterKey的任何更改(在data()中定义的)触发的,因此局部变量也会被更新,尽管它们在Vue方式上不是“反应性”的。
在计算属性中定义局部变量时,对性能有任何影响吗?您是否应该直接在计算属性中使用来自data() (例如,this.filterKey)的反应变量?
发布于 2018-09-12 16:31:19
测试某件事是否影响性能的最好方法是实际测试它。
根据下面的测试,使用this.passedData比在函数顶部添加变量慢1000%以上。(869 vs Vs 29 Vs)
确保在目标浏览器上运行基准测试,编写应用程序以获得最佳结果。
function time(name, cb) {
var t0 = performance.now();
const res = cb();
if(res !== 20000000) {
throw new Error('wrong result: ' + res);
}
var t1 = performance.now();
document.write("Call to "+name+" took " + (t1 - t0) + " milliseconds.<br>")
}
function withoutLocalVar() {
const vue = new Vue({
computed: {
hi() {
return 1;
},
hi2() {
return 1;
},
test() {
let sum = 0;
for(let i = 0; i < 10000000; i++) { // 10 000 000
sum += this.hi + this.hi2;
}
return sum;
},
}
})
return vue.test;
}
function withLocalVar() {
const vue = new Vue({
computed: {
hi() {
return 1;
},
hi2() {
return 1;
},
test() {
let sum = 0;
const hi = this.hi;
const hi2 = this.hi2;
for(let i = 0; i < 10000000; i++) { // 10 000 000
sum += hi + hi2;
}
return sum;
},
}
})
return vue.test;
}
function benchmark() {
const vue = new Vue({
computed: {
hi() {
return 1;
},
hi2() {
return 1;
},
test() {
let sum = 0;
const hi = 1;
const hi2 = 1;
for(let i = 0; i < 10000000; i++) { // 10 000 000
sum += hi + hi2;
}
return sum;
},
}
})
return vue.test;
}
time('withoutLocalVar - init', withoutLocalVar);
time('withLocalVar - init', withLocalVar);
time('benchmark - init', benchmark);
time('withoutLocalVar - run1', withoutLocalVar);
time('withLocalVar - run1', withLocalVar);
time('benchmark - run1', benchmark);
time('withoutLocalVar - run2', withoutLocalVar);
time('withLocalVar - run2', withLocalVar);
time('benchmark - run2', benchmark);<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
https://stackoverflow.com/questions/52299407
复制相似问题