我的代码太慢了,但我不确定如何改进它。从磁盘读取到1k文件的DOM需要大约20 ms,这可能是好的,具体取决于磁盘,但是接下来我还有20 ms用于处理xpath语句,这太多了。以下是一些带有时间注释的示例代码。我如何改进代码?优化DOM和XPath Java代码
这发生在施工时间:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = this.dbFactory.newDocumentBuilder();
XPathExpression[] ex = new XPathExpression[]{about 30 different expressions}
XPathExpression mainEx =xPath.compile("/rootElement/firstLevel/secondLevel");
然后代码:
Document doc = this.dBuilder.parse("somefile.xml");
//took 20 ms until here
NodeList nodes = (NodeList) mainEx .evaluate,doc, XPathConstants.NODESET);
//took another 20 ms until here !!!
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
for (XPathExpression e:ex) {
String v = (String) e.evaluate(n, XPathConstants.STRING);
if (v != null) {
System.out.println(v);
}
}
}
//this only takes 5 ms
可能与http://stackoverflow.com/questio相关ns/6340802/java -xpath-apache-jaxp-implementation-performance –
切换到VTD-XML <您的问题将消失 –