Difference between newTransformer and newTemplates in Java XSLT transformations

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?

1

3 Answers

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.

0

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...

1

newTemplates() compiles the stylesheet into an internal representation that can be reused. It's the equivalent of compiling an interpreted language (like Python) to bytecode and saving the bytecode, as opposed to reinterpreting it each time you run it.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like