我已經(jīng)做了一些基本的基準(zhǔn)測(cè)試,想知道是否應(yīng)該提供/注入經(jīng)常使用的變量,或者是否應(yīng)該從大量組件中的 Pinia 商店訪問(wèn)它們。
結(jié)果表明,沒(méi)有顯著的表現(xiàn)差異。
我的第一個(gè)測(cè)試案例非?;荆?提供/注入單一 bool
與從元件中的 Pinia 儲(chǔ)存空間取得它並多次渲染元件不同。
50k 元件渲染花費(fèi)的時(shí)間在 20-24 秒之間,使用提供/注入和使用 Pinia 時(shí)也是如此。沒(méi)有一致的差異可以說(shuō)兩者中的任何一個(gè)更快/更慢。
在第二個(gè)測(cè)試中,我使用了一個(gè)更大的對(duì)象,一個(gè)大約 1MiB 資料的陣列(以無(wú)空格 JSON 列印測(cè)量)。差異同樣不顯著。我已經(jīng)渲染了 50k 元件,並且使用注入和儲(chǔ)存存取都花費(fèi)了大約相同的時(shí)間,在 19-26 秒之間。
每種情況下的元件都會(huì)渲染主題變數(shù)的布林值,因此它們的渲染時(shí)間不會(huì)因大數(shù)據(jù)與小布林值而增加。
畢竟,我得出的結(jié)論是,provide/inject 與 Pinia 商店之間確實(shí)沒(méi)有任何有意義的區(qū)別。唯一明顯的差異是,當(dāng)資料較大時(shí),效能較不穩(wěn)定,當(dāng)資料較小時(shí),效能更可預(yù)測(cè)。無(wú)論我對(duì)布林值重複測(cè)試多少次,時(shí)間總是在 20-24 秒之間,隨著資料的增加,我得到了一些異常值,例如 19 秒或 26 秒。再次沒(méi)有一致的情況,這可能只是我實(shí)際 CPU 使用率的波動(dòng),與 Provide/inject 與 Pinia store 的使用情況無(wú)關(guān)。
我使用 vue@3.2.47 和 pinia@2.0.32 在 macOS 上的 Chrome v110 (x86_64) 上進(jìn)行了測(cè)試。
我使用的測(cè)試程式碼:
<template> <div>Inject {{ number }}: {{ injected ? 'yes' : 'no' }}</div> </template> <script setup lang="ts"> export interface Props { number?: number, } const props = withDefaults( defineProps<Props>(), { number: 0, }) import { inject } from 'vue' const injected = inject('inject-test') </script>
<template> <div>Store get {{ number }}: {{ testStore.test ? 'yes' : 'no' }}</div> </template> <script setup lang="ts"> export interface Props { number?: number, } const props = withDefaults( defineProps<Props>(), { number: 0, }) import { useTestStore } from 'stores/test' const testStore = useTestStore() </script>
<template> <div v-if="testStore"> <h1>Store get</h1> <pre>Start: {{ start() }}</pre> <div class="test"> <StoreGet v-for="n in 50000" :key="n" :number="n" /> </div> <pre>End: {{ end() }}</pre> <pre>Duration: {{ endTime - startTime }} seconds</pre> </div> <div v-else> <h1>Inject</h1> <pre>Start: {{ start() }}</pre> <div class="test"> <Inject v-for="n in 50000" :key="n" :number="n" /> </div> <pre>End: {{ end() }}</pre> <pre>Duration: {{ endTime - startTime }} seconds</pre> </div> </template> <script setup lang="ts"> import { provide } from 'vue' import Inject from './test/Inject.vue' import StoreGet from './test/StoreGet.vue' // Roughly 1M of json data import { large } from '@sbnc/datasets/largeTest' // Comment one or the other: const testData = true //const testData = large // Choose which one to test: const testStore = true // set false to test inject provide( 'inject-test', testData) import { useTestStore } from 'stores/test' const testStore = useTestStore() testStore.test = testData let startTime let endTime function start() { startTime = performance.now() return startTime } function end() { endTime = performance.now() return endTime } </script>