Difference between newTransformer and newTemplates in Java XSLT transformations

In Java, from TransformerFactory to create objects for processing XSLT, and it has methods:

  • newTransformer , which creates a Transformer object that can transform the XML into a result.
  • newTemplates , which creates a Templates object that Transformer can create.

The documentation for Transformer explicitly states:

The transformer can be used several times.

My application processes various XML files with the same XSLT. At the beginning of the program, I use newTransformer to create a Transformer , and then reuse it for all XML files (make sure it is synchronized, so I use it from only one thread and calling its reset() method before each processing.).

Thus, I do not incur the cost of recompiling XSLT for each XML I process.

So what is the point of the newTemplates and Templates object? Should I use this instead and create a new Transformer object for each XML?

+8
java xml xslt saxon
source share
3 answers

If you work on the same thread, you probably won't notice much of a difference.

Performance always depends on the implementation, not the API specification. With Saxon, when you use Transformer again, it saves the cache of documents loaded with the doc () function. This can be good or bad depending on whether the next conversion will have access to the same source documents. As a rule, I advise you to use the new Transformer for each transformation, but, of course, using the same Templates object.

+6
source share

The main difference is that Templates is thread safe, while Transformer is not. In addition, the documentation implies that performance optimization can be applied during the instantiation of Templates . Thus, initial instantiation of Templates can be more expensive, but actual use can provide performance gains. If you already need to manually manage synchronization and reset, I would say that Templates asks for your attention ...

+6
source share

newTemplates () compiles the stylesheet into an internal view that can be reused. This is the equivalent of compiling an interpreted language (such as Python) for bytecode and storing the bytecode, as opposed to re-interpreting it every time you run it.

+4
source share

All Articles