Skip to content

Commit

Permalink
perf(runtime-core): use for of to replace for loop
Browse files Browse the repository at this point in the history
  • Loading branch information
chenfan0 committed Sep 25, 2024
1 parent a177092 commit 3bc58c5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 19 deletions.
34 changes: 34 additions & 0 deletions packages/reactivity/__benchmarks__/reactiveArray.bench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,38 @@ for (let amount = 1e1; amount < 1e4; amount *= 10) {
arr.push(1)
})
}

{
const rawArray: number[] = []
for (let i = 0, n = amount; i < n; i++) {
rawArray.push(i)
}
const arr = reactive(rawArray)

bench(`normal for loop, ${amount} elements`, () => {
let sum = 0
effect(() => {
for (let i = 0; i < arr.length; i++) {
sum += arr[i]
}
})
})
}

{
const rawArray: number[] = []
for (let i = 0, n = amount; i < n; i++) {
rawArray.push(i)
}
const arr = reactive(rawArray)

bench(`for...of loop, ${amount} elements`, () => {
let sum = 0
effect(() => {
for (const item of arr) {
sum += item
}
})
})
}
}
24 changes: 5 additions & 19 deletions packages/runtime-core/src/helpers/renderList.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import type { VNode, VNodeChild } from '../vnode'
import {
isReactive,
isShallow,
shallowReadArray,
toReactive,
} from '@vue/reactivity'
import { isArray, isObject, isString } from '@vue/shared'
import { warn } from '../warning'

Expand Down Expand Up @@ -67,20 +61,12 @@ export function renderList(
const sourceIsArray = isArray(source)

if (sourceIsArray || isString(source)) {
const sourceIsReactiveArray = sourceIsArray && isReactive(source)
let needsWrap = false
if (sourceIsReactiveArray) {
needsWrap = !isShallow(source)
source = shallowReadArray(source)
}
ret = new Array(source.length)
for (let i = 0, l = source.length; i < l; i++) {
ret[i] = renderItem(
needsWrap ? toReactive(source[i]) : source[i],
i,
undefined,
cached && cached[i],
)
let i = 0

for (const sourceItem of source) {
ret[i] = renderItem(sourceItem, i, undefined, cached && cached[i])
i++
}
} else if (typeof source === 'number') {
if (__DEV__ && !Number.isInteger(source)) {
Expand Down

0 comments on commit 3bc58c5

Please # to comment.