Skip to content

Commit

Permalink
perf: improve getTemplate() when cache is enabled
Browse files Browse the repository at this point in the history
Checking for file existence is unnecessary when cache contains entry.
  • Loading branch information
pmalouin authored and harttle committed Jun 17, 2019
1 parent bbebb55 commit 1ffba2b
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 1 deletion.
2 changes: 2 additions & 0 deletions benchmark/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import output from './output'
import tag from './tag'
import demo from './demo'
import layout from './layout'

async function main () {
await output()
await tag()
await demo()
await layout()
}

main()
36 changes: 36 additions & 0 deletions benchmark/layout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import * as Benchmark from 'benchmark'
import Liquid from '../src/liquid'

const engineOptions = {
root: __dirname,
extname: '.liquid'
}

const engine = new Liquid(engineOptions)
const cachingEngine = new Liquid({
...engineOptions,
cache: true
})

const template = `
{% layout "./templates/layout.liquid" %}
{% block body %}a small body{% endblock %}
`

export default function () {
console.log('--- layout ---')
return new Promise(resolve => {
new Benchmark.Suite('layout')
.add('cache=false', {
defer: true,
fn: (d: any) => engine.parseAndRender(template, {}).then(x => d.resolve(x))
})
.add('cache=true', {
defer: true,
fn: (d: any) => cachingEngine.parseAndRender(template, {}).then(x => d.resolve(x))
})
.on('cycle', (event: any) => console.log(String(event.target)))
.on('complete', resolve)
.run({ 'async': true })
})
}
2 changes: 2 additions & 0 deletions benchmark/templates/layout.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This is a barely empty layout with a body:
{% block body %}{% endblock %}
3 changes: 2 additions & 1 deletion src/liquid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,10 @@ export default class Liquid {
const paths = roots.map(root => fs.resolve(root, file, this.options.extname))

for (const filepath of paths) {
if (this.options.cache && this.cache[filepath]) return this.cache[filepath]

if (!(await fs.exists(filepath))) continue

if (this.options.cache && this.cache[filepath]) return this.cache[filepath]
const value = this.parse(await fs.readFile(filepath), filepath)
if (this.options.cache) this.cache[filepath] = value
return value
Expand Down

0 comments on commit 1ffba2b

Please sign in to comment.