From 136a2fd31c25f19404dffc0cc2f8172631973956 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 14 Aug 2017 07:29:34 -0400 Subject: [PATCH] only cache values if necessary --- .../dom/visitors/Component/Component.ts | 2 +- src/generators/dom/visitors/MustacheTag.ts | 27 ++++++++++++------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/generators/dom/visitors/Component/Component.ts b/src/generators/dom/visitors/Component/Component.ts index a9fff4ee39..56681ddcf6 100644 --- a/src/generators/dom/visitors/Component/Component.ts +++ b/src/generators/dom/visitors/Component/Component.ts @@ -212,7 +212,7 @@ export default function visitComponent( ${updates.join('\n')} - if ( Object.keys( ${name}_changes ).length ) ${name}._set( ${name}_changes ); + ${name}._set( ${name}_changes ); `); } diff --git a/src/generators/dom/visitors/MustacheTag.ts b/src/generators/dom/visitors/MustacheTag.ts index 355e3b99fc..77c84d3330 100644 --- a/src/generators/dom/visitors/MustacheTag.ts +++ b/src/generators/dom/visitors/MustacheTag.ts @@ -10,17 +10,21 @@ export default function visitMustacheTag( state: State, node: Node ) { + const { dependencies, snippet } = block.contextualise(node.expression); + + const shouldCache = node.expression.type !== 'Identifier' || block.contexts.has(node.expression.name); + const name = node._state.name; - const value = block.getUniqueName(`${name}_value`); + const value = shouldCache && block.getUniqueName(`${name}_value`); + const init = shouldCache ? `${value} = ${snippet}` : snippet; - const { dependencies, snippet } = block.contextualise(node.expression); + if (shouldCache) block.addVariable(value); - block.addVariable(value); block.addElement( name, - `@createText( ${value} = ${snippet} )`, + `@createText( ${init} )`, generator.hydratable - ? `@claimText( ${state.parentNodes}, ${value} = ${snippet} )` + ? `@claimText( ${state.parentNodes}, ${init} )` : '', state.parentNode, true @@ -32,10 +36,13 @@ export default function visitMustacheTag( dependencies.map(dependency => `'${dependency}' in changed`).join(' || ') ); - block.builders.update.addBlock(deindent` - if ( ( ${changedCheck} ) && ${value} !== ( ${value} = ${snippet} ) ) { - ${name}.data = ${value}; - } - `); + const condition = shouldCache ? + `( ${changedCheck} ) && ${value} !== ( ${value} = ${snippet} )` : + changedCheck; + + block.builders.update.addConditionalLine( + condition, + `${name}.data = ${shouldCache ? value : snippet};` + ); } }