Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(runtime-core): use for of to replace for loop #12024

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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