Here is our use case. We are loading freemarker syntax from the database and processing it. We are processing close to a million of records. Things are working fine. But when I profile the application, I see that my freemarker processing method is the bottleneck and it is taking most time. Having read the freemarker documentation, I got some pointers on what my issue would be. Everytime I am doing processing, I am creating new freemarker.template.Template object (creation of which seems expensive). I could not find what would be the right/more efficient way of doing this.
public FTLTemplateEngine() { cfg = new Configuration(); } public String process(String template, Map<String, Object> input) throws IOException, TemplateException { String rc = null; final Writer out = new StringWriter(); try { final Template temp =new Template("TemporaryTemplate", new StringReader(template), cfg); temp.process(input, out); } catch (InvalidReferenceException e) { log.error("Unable to process FTL - " + template); throw new InvalidReferenceException("FTL expression has evaluated to null or it refers to something that doesn't exist. - " + template, Environment.getCurrentEnvironment()); } catch (TemplateException e) { log.error("Unable to process FTL - " + template); throw new TemplateException("Unable to process FTL - " + template, e, Environment.getCurrentEnvironment()); } catch (IOException e) { log.error("Unable to process FTL - " + template); throw new IOException("Unable to process FTL - " + template); } rc = out.toString(); out.close(); return rc.trim(); }
Have a look the process method which is called every time Freemarker needs to be parsed. In this method we are creating new Template object everytime. Is there a way to avoid this?
AFAIR you normally don't call the Template
constructor directly, but use a Configuration
instance to do that (see Get the template and Template loading). The Configuration
object also employs caching, which could help. You might need to write your own TemplateLoader
in order to load your FreeMarker templates from the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With