perf: improve static content insertion perf

Especially on multiple insertions of the same static node.

fix #3090
This commit is contained in:
Evan You
2021-06-21 14:34:08 -04:00
parent be1e42eb92
commit 4de5d24aa7
3 changed files with 151 additions and 21 deletions

View File

@@ -4,9 +4,6 @@ export const svgNS = 'http://www.w3.org/2000/svg'
const doc = (typeof document !== 'undefined' ? document : null) as Document
let tempContainer: HTMLElement
let tempSVGContainer: SVGElement
export const nodeOps: Omit<RendererOptions<Node, Element>, 'patchProp'> = {
insert: (child, parent, anchor) => {
parent.insertBefore(child, anchor || null)
@@ -71,23 +68,54 @@ export const nodeOps: Omit<RendererOptions<Node, Element>, 'patchProp'> = {
},
// __UNSAFE__
// Reason: innerHTML.
// Reason: insertAdjacentHTML.
// Static content here can only come from compiled templates.
// As long as the user only uses trusted templates, this is safe.
insertStaticContent(content, parent, anchor, isSVG) {
const temp = isSVG
? tempSVGContainer ||
(tempSVGContainer = doc.createElementNS(svgNS, 'svg'))
: tempContainer || (tempContainer = doc.createElement('div'))
temp.innerHTML = content
const first = temp.firstChild as Element
let node: Element | null = first
let last: Element = node
while (node) {
last = node
nodeOps.insert(node, parent, anchor)
node = temp.firstChild as Element
insertStaticContent(content, parent, anchor, isSVG, cached) {
if (cached) {
let [cachedFirst, cachedLast] = cached
let first, last
while (true) {
let node = cachedFirst.cloneNode(true)
if (!first) first = node
parent.insertBefore(node, anchor)
if (cachedFirst === cachedLast) {
last = node
break
}
cachedFirst = cachedFirst.nextSibling!
}
return [first, last] as any
}
return [first, last]
// <parent> before | first ... last | anchor </parent>
const before = anchor ? anchor.previousSibling : parent.lastChild
if (anchor) {
let insertionPoint
let usingTempInsertionPoint = false
if (anchor instanceof Element) {
insertionPoint = anchor
} else {
// insertAdjacentHTML only works for elements but the anchor is not an
// element...
usingTempInsertionPoint = true
insertionPoint = isSVG
? doc.createElementNS(svgNS, 'g')
: doc.createElement('div')
parent.insertBefore(insertionPoint, anchor)
}
insertionPoint.insertAdjacentHTML('beforebegin', content)
if (usingTempInsertionPoint) {
parent.removeChild(insertionPoint)
}
} else {
parent.insertAdjacentHTML('beforeend', content)
}
return [
// first
before ? before.nextSibling : parent.firstChild,
// last
anchor ? anchor.previousSibling : parent.lastChild
]
}
}