Skip to content

Commit

Permalink
Reuse a single TreeWalker in nested templates (lit#825)
Browse files Browse the repository at this point in the history
Creating `TreeWalker`s isn't very optimized, so reusing a single one in the nested templates can speed it up a bit.

https://jsbench.github.io/#d0363ded1753dec3e060e61e1794896b
  • Loading branch information
jridgewell authored and justinfagnani committed Feb 27, 2019
1 parent c25532d commit 865e19b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
15 changes: 8 additions & 7 deletions src/lib/template-instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,14 @@ export class TemplateInstance {
const parts = this.template.parts;
let partIndex = 0;
let nodeIndex = 0;
// Edge needs all 4 parameters present; IE11 needs 3rd parameter to be null
const walker = document.createTreeWalker(
document,
133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */,
null,
false);
const _prepareInstance = (fragment: DocumentFragment) => {
// Edge needs all 4 parameters present; IE11 needs 3rd parameter to be
// null
const walker = document.createTreeWalker(
fragment,
133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */,
null,
false);
walker.currentNode = fragment;
let node = walker.nextNode();
// Loop through all the nodes and parts of a template
while (partIndex < parts.length && node !== null) {
Expand Down Expand Up @@ -103,6 +103,7 @@ export class TemplateInstance {
nodeIndex++;
if (node.nodeName === 'TEMPLATE') {
_prepareInstance((node as HTMLTemplateElement).content);
walker.currentNode = node;
}
node = walker.nextNode();
}
Expand Down
16 changes: 8 additions & 8 deletions src/lib/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,14 @@ export class Template {
let index = -1;
let partIndex = 0;
const nodesToRemove: Node[] = [];
// Edge needs all 4 parameters present; IE11 needs 3rd parameter to be null
const walker = document.createTreeWalker(
document,
133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */,
null,
false);
const _prepareTemplate = (template: HTMLTemplateElement) => {
const content = template.content;
// Edge needs all 4 parameters present; IE11 needs 3rd parameter to be
// null
const walker = document.createTreeWalker(
content,
133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */,
null,
false);
walker.currentNode = template.content;
// Keeps track of the last index associated with a part. We try to delete
// unnecessary nodes, but we never want to associate two different parts
// to the same index. They must have a constant node between.
Expand Down Expand Up @@ -103,6 +102,7 @@ export class Template {
}
if ((node as Element).tagName === 'TEMPLATE') {
_prepareTemplate(node as HTMLTemplateElement);
walker.currentNode = node;
}
} else if (node.nodeType === 3 /* Node.TEXT_NODE */) {
const data = (node as Text).data!;
Expand Down

0 comments on commit 865e19b

Please sign in to comment.