Lazy load Reader
Motivation:
PebbleEngine currently eager loads a Reader on every getTemplate call, even though the compiled template might end up being already present in the cache.
Modification:
When a cache is present, only create the Reader on cache miss.
Result:
Faster `getTemplate` when compiled template is already in cache.
@@ -142,28 +142,20 @@ public class PebbleEngine {
throw new LoaderException(null, "Loader has not yet been specified.");
}
- PebbleTemplate result;
-
Object cacheKey = loader.createCacheKey(templateName);
- Reader templateReader = loader.getReader(cacheKey);
- try {
+
if (isNull(this.templateCache)) {
- result = this.getPebbleTemplate(this, templateName, templateReader);
+ return getPebbleTemplate(templateName, loader, cacheKey);
} else {
- result = this.templateCache.get(cacheKey, k -> this.getPebbleTemplate(this, templateName, templateReader));
- }
- } finally {
- try {
- templateReader.close();
- } catch (IOException e) {
- // can't do much about it
+ return this.templateCache.get(cacheKey, k -> getPebbleTemplate(templateName, loader, cacheKey));
}
}
- return result;
- }
+ private PebbleTemplate getPebbleTemplate(String templateName, Loader loader, Object cacheKey) {
- private PebbleTemplate getPebbleTemplate(PebbleEngine self, String templateName, Reader templateReader) {
+ Reader templateReader = loader.getReader(cacheKey);
+
+ try {
LexerImpl lexer = new LexerImpl(this.syntax, this.extensionRegistry.getUnaryOperators().values(),
this.extensionRegistry.getBinaryOperators().values());
TokenStream tokenStream = lexer.tokenize(templateReader, templateName);
@@ -172,13 +164,21 @@ public class PebbleEngine {
this.extensionRegistry.getBinaryOperators(), this.extensionRegistry.getTokenParsers(), this.parserOptions);
RootNode root = parser.parse(tokenStream);
- PebbleTemplateImpl instance = new PebbleTemplateImpl(self, root, templateName);
+ PebbleTemplateImpl instance = new PebbleTemplateImpl(this, root, templateName);
for (NodeVisitorFactory visitorFactory : this.extensionRegistry.getNodeVisitors()) {
visitorFactory.createVisitor(instance).visit(root);
}
return instance;
+
+ } finally {
+ try {
+ templateReader.close();
+ } catch (IOException e) {
+ // can't do much about it
+ }
+ }
}
/**
