【发布时间】:2021-04-10 16:15:16
【问题描述】:
我正在开发一个存在性能问题的 Vue/Vuetify 应用程序。我创建了一个环绕a standard Vuetify v-data-table component 的自定义组件。它适用于少量数据,但提供中到大量数据会导致 Firefox 挂起,Chrome 崩溃。
这是我的代码的稍微简化的版本:
<script>
import ...
export default {
props: {
theValues: Array,
// other props
},
computed: {
theKeys: function() {
return this.schema.map(col => col.col);
},
schema: function() {
return this.theValues[0].schema;
},
dataForDataTable: function() {
console.time('test');
let result = [];
for (let i = 0; i < theValues[0].data.length; i++) {
let resultObj = {};
for (let j = 0; j < theKeys.length; j++) {
// The "real" logic; this causes the browser to hang/crash
// resultObj[theKeys[j]] = theValues[0].data[i][j];
// Test operation to diagnose the problem
resultObj[theKeys[j]] = Math.floor(Math.random() * Math.floor(99999));
}
result.push(resultObj);
}
console.timeEnd('test');
// For ~30k rows, timer reports that:
// Real values can take over 250,000 ms
// Randomly generated fake values take only 7 ms
return result;
},
// other computed
},
// other Vue stuff
</script>
下面是theValues 实际外观的示例:
[
{
data: [
[25389, 24890, 49021, ...] <-- 30,000 elements
],
schema: [
{
col: "id_number",
type: "integer"
}
]
}
]
我看到的快速代码和慢速代码之间唯一有意义的区别是,慢速代码在每次迭代时都会访问 prop theValues,而快速代码不会触及 Vue 的任何复杂部分。 (它确实使用了theKeys,但即使我在函数内部创建了theKeys 的本地深层副本,性能也不会改变。)
基于此,问题似乎不是数据表组件无法处理我发送的数据量,或者嵌套循环本身效率太低。我最好的猜测是,从 props 中读取这么多内容会以某种方式减慢 Vue 本身的速度,但我不能 100% 确定这一点。
但我最终确实需要从道具中获取信息到表格中。我该怎么做才能以合理的速度加载?
【问题讨论】:
-
我想知道它是否与访问道具有关。您可以尝试拉出循环不变部分吗?在循环之前
const thePropData = theValues[0].data;,然后在循环中thePropData[i][j]。这有什么不同吗? (哦,还有迭代检查i < thePropData.length) -
为什么需要遍历
theKeys数组?为什么不使用 vuejs 提供的响应性? -
我已经尝试过类似的方法,将调用拉出内循环,而不是外循环。它没有任何区别,事后看来,这是因为在简化的示例中只有一列。把它拉到更上一层,从外循环中出来,就可以了。作为答案发布?
-
@Danizavtz 抱歉,我不明白你的建议是什么?
标签: javascript performance vue.js vuetify.js