In Java, from a TransformerFactory
for creating objects to process XSLT, and it has the methods:
newTransformer
which creates Transformer
object, which can transform XML into a result.newTemplates
which creates Templates
object which can create a Transformer
.The documentation for Transformer
explicitly states:
A Transformer may be used multiple times.
My application processes various different XMLs with the same XSLT. At the start of the program I use newTransformer
to create a Transformer
then re-use it for all the XMLs (making sure it's synchronized so I only use it from one thread; and calling its reset()
method before each processing.).
That way I don't incur the cost of re-compiling the XSLT for every XML I process.
So what's the point of the newTemplates
and the Templates
object? Should I be using that instead, and creating a new Transformer
object for each XML?
A TransformerFactory instance can be used to create Transformer and Templates objects. The system property that determines which Factory implementation to create is named "javax. xml. transform.
A TransformerFactory is used to create Transformer objects that perform document transformations, and can also be used to process transformation instructions (such as XSLT stylesheets) into compiled Templates objects. Obtain a TransformerFactory instance by calling the static newInstance( ) method.
An implementation of the TransformerFactory class is NOT guaranteed to be thread safe. It is up to the user application to make sure about the use of the TransformerFactory from more than one thread. Alternatively the application can have one instance of the TransformerFactory per thread.
The main difference is that Templates
is thread-safe and Transformer
is not. In addition, the documentation implies that performance optimizations may be applied during the creation of a Templates
instance. So, the initial creation of a Templates
instance may be more costly, but it's actual usage can offer performance gains. If you're already having to manually manage synchronization and resets, I'd say Templates
is begging for your attention...
If you're running in a single thread, then you probably won't notice much difference.
Performance always depends on the implementation rather than on the API specification. With Saxon, when you reuse a Transformer, it retains the cache of documents loaded using the doc() function. That may be good or bad depending on whether the next transformation is going to access the same source documents. Generally my advice is to use a new Transformer for each transformation, but using the same Templates object, of course.
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