vue3 中 ref/shallowRef/reactive/shallowReactive 性能对比

179 阅读1分钟

测试代码 测试一个数组,数据量为10万

import { ref, shallowRef, reactive, shallowReactive } from 'vue';

const arr = shallowRef([]);

const arrComputed = computed(() => {
	return arr.value.slice(0, 10);
});

const length = 10000 * 10;

console.time('shallowRef');
new Array(length).fill('').forEach((_, i) => {
	arr.value.push({ label: `${1}label`, value: i, info: { name: '1', value: 1 } });
});
console.timeEnd('shallowRef');

const arr1 = ref([]);

console.time('ref');
new Array(length).fill('').forEach((_, i) => {
	arr1.value.push({ label: `${1}label`, value: i, info: { name: '1', value: 1 } });
});
console.timeEnd('ref');

const arr2 = reactive({
	list: [],
});
console.time('reactive');
new Array(length).fill('').forEach((_, i) => {
	arr2.list.push({ label: `${1}label`, value: i, info: { name: '1', value: 1 } });
});
console.timeEnd('reactive');

const arr3 = shallowReactive({
	list: [],
});
console.time('shallowReactive');
new Array(length).fill('').forEach((_, i) => {
	arr3.list.push({ label: `${1}label`, value: i, info: { name: '1', value: 1 } });
});
console.timeEnd('shallowReactive');
# 输出
>
shallowRef: 2.27001953125 ms
ref: 221.6220703125 ms
reactive: 225.02294921875 ms
shallowReactive: 8.682861328125 ms

可以看到数量为10w时,性能为 shallowRef ≈ shallowReactive > ref ≈ reactive

因为shallowRef/shallowReactive只是对.value浅层代理,性能好很多, 在数据量大时(比如表格、下拉列表)优先考虑shallow类响应式API