开发者

Java: need help with optimizing a part of code

开发者 https://www.devze.com 2023-03-02 10:17 出处:网络
I have a simple code for transforming XML, but it is very time consuming (I have to repeat it many times). Does anyone have a recommendation how to optimize this code? Thanks.

I have a simple code for transforming XML, but it is very time consuming (I have to repeat it many times). Does anyone have a recommendation how to optimize this code? Thanks.

EDIT: This is a new version of the code. I unfortunatelly can't reuse Transformer, since XSLTRuleis in most of the cases different. I'm now reusing TransformerFactory. I'm not reading from files before this so I can't use StreamSource. Largest amount of time is spent on initialization of Transformer.

private static TransformerFactory tFactory = TransformerFactory.newInstance();

public static String transform(String XML, String XSLTRule) throws TransformerException {

    Source xmlInput = new StreamSource(new StringReader(XML));
    Source xslInput = new St开发者_开发知识库reamSource(new StringReader(XSLTRule));

    Transformer transformer = tFactory.newTransformer(xslInput);

    StringWriter resultWriter = new StringWriter();
    Result result = new StreamResult(resultWriter);
    transformer.transform(xmlInput, result);
    return resultWriter.toString();
}


The first thing you should do is to skip the unnecessary conversion of the XML string to bytes (especially with a hardcoded, potentially incorrect encoding). You can use a StringReader and pass that to the StreamSource constructor. The same for the result: use a StringWriter and avoid the conversion.

Of course, if you call the method after converting your XML from a file (bytes) to a String in the first place (again with a potentially wrong encoding), it would be even better to have the StreamSource read from the file directly.


It seems like you apply an XSLT to an XML file. To speed things up, you can try compiling the XSLT, like with XSLTC.


I can only think of a couple of minor things:

  • The TransformerFactory could be reused.

  • The Transformer could be reused if it is thread confined, and the XSL input is the same each time.

  • If you can estimate the output size reasonably accurately, you could create the ByteArrayOutputStream with an initial size hint.


As stated in Michaels answer, you could potentially speed things up by not loading either the input or output xml entirely into memory yourself and make your api stream based.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号