Skip to content

Commit d7dc7fd

Browse files
authored
Merge pull request #321 from zheksoon/master
improve performance of updateElement
2 parents 3f4996d + 616fa36 commit d7dc7fd

File tree

1 file changed

+27
-9
lines changed

1 file changed

+27
-9
lines changed

src/dom.ts

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,40 @@
11
import { Attributes, DOM, IFiber } from "./type"
22
import { isStr, LANE } from "./reconcile"
33

4+
const hasOwnProperty = Object.prototype.hasOwnProperty;
5+
6+
const defaultObj = {} as const;
7+
8+
const jointIter = <P extends Attributes>(
9+
aProps = defaultObj as P,
10+
bProps = defaultObj as P,
11+
callback: (name: string, a: any, b: any) => void
12+
) => {
13+
for (const name in aProps) {
14+
if (hasOwnProperty.call(aProps, name)) {
15+
callback(name, aProps[name], bProps[name]);
16+
}
17+
}
18+
for (const name in bProps) {
19+
if (hasOwnProperty.call(bProps, name) && !hasOwnProperty.call(aProps, name)) {
20+
callback(name, undefined, bProps[name]);
21+
}
22+
}
23+
}
24+
425
export const updateElement = <P extends Attributes>(
526
dom: DOM,
627
aProps: P,
728
bProps: P
829
) => {
9-
for (let name in { ...aProps, ...bProps }) {
10-
let a = aProps[name]
11-
let b = bProps[name]
12-
30+
jointIter(aProps, bProps, (name, a, b) => {
1331
if (a === b || name === "children") {
1432
} else if (name === "style" && !isStr(b)) {
15-
for (const k in { ...a, ...b }) {
16-
if (!(a && b && a[k] === b[k])) {
17-
; (dom as any)[name][k] = b?.[k] || ""
33+
jointIter(a, b, (styleKey, aStyle, bStyle) => {
34+
if (aStyle !== bStyle) {
35+
; (dom as any)[name][styleKey] = bStyle || ""
1836
}
19-
}
37+
})
2038
} else if (name[0] === "o" && name[1] === "n") {
2139
name = name.slice(2).toLowerCase() as Extract<keyof P, string>
2240
if (a) dom.removeEventListener(name, a)
@@ -28,7 +46,7 @@ export const updateElement = <P extends Attributes>(
2846
} else {
2947
dom.setAttribute(name, b)
3048
}
31-
}
49+
})
3250
}
3351

3452
export const createElement = <P = Attributes>(fiber: IFiber) => {

0 commit comments

Comments
 (0)