9

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?

Flack
  • 5,862
  • 2
  • 23
  • 27
Adrian Smith
  • 17,236
  • 11
  • 71
  • 93

3 Answers3

7

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

kschneid
  • 5,626
  • 23
  • 31
7

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.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
4

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.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • How would you compare that with what `newTransformer` does, surely that's what it does as well? – Adrian Smith Mar 11 '11 at 21:21
  • Yes, but it doesn't save the compiled stylesheet – Jim Garrison Mar 11 '11 at 21:59
  • If you reuse the `Transformer` object, then it only compiles the stylesheet once, so in that sense `newTransfomer` compile and save the compiled stylesheet, just as `newTemplates` does (or did I misunderstand something?) – Adrian Smith Mar 13 '11 at 12:37