[gatein-dev] Groovy template engine rewrite

Julien Viet julien at julienviet.com
Sun Nov 1 18:25:25 EST 2009


In my optimization effort I have rewritten the Groovy Template engine  
from scratch.

The previous engine was a fork of the basic SimpleTemplateEngine in  
the Groovy package (why it was forked ? I haven't had an answer so far).

One part of the optimization consist into translating the markup  
chunks of the template directly into UTF-8 encoded bytes so it can be  
directly written on the Servlet output stream. Actually if you think  
about it, on every request constants character data (the markup  
chunks) are converted into byte using the UTF-8 encoding. So it has 2  
nasty effects:

1/ encoding a char into a byte[] (some chars take several bytes) is  
costly specially if the Servlet engine do it for you (as it is  
possible to optimize it and that's what we do in other parts of GateIn)

2/ unnecessary serialization as when you encode the string GateIn  
basically you
- write the char[] on the Writer
- tomcat read the char[]
- tomcat translate each char into a byte[]
- the corresponding byte[] is written to the output (with usually an  
additional buffer)

The Groovy markup chunk optimization computes the byte[] and write  
them to the servlet output, removing the cost of doing the translation  
to byte[] (encoding) and a read/write of the array (serialization).

The second part of the optimization is to pre parse directly the  
Groovy strings (known as GString). As you may know in Groovy it is  
possible to have $foo or ${foo} into the markup which cause an  
evalutation of the string. The new template compiler pre parse that  
into expression and markup chunks.

The benefit of template rewrite in the capability to maintain a table  
of template line number to groovy line number which allowed me to  
implement more precise error reporting when an exception occurs, for  
instance:

1. abc <% throw new Exception(); %> def

is compiled into Groovy like:

1. out.print("abc");
2. throw new Exception();
3. out.print("def");

So when the exception occurs, Groovy say the error happened at line 2  
but what interest us is where it happened in the template file.

So I have been able to craft that into the engine and normally it  
should work better (I'm saying that because I have unit tests but I'm  
not 100% sure that I cover all cases).

cheers

Julien


More information about the gatein-dev mailing list