我的代碼太慢了,但我不確定如何改進它。從磁盤讀取到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 <您的問題將消失 –