我的代码太慢了,但我不知道如何改进它。将 1k 文件从磁盘读取到 DOM 大约需要 20 毫秒,这取决于磁盘可能没问题,但是我还有 20 毫秒来处理 xpath 语句,这太多了。这是一些带有时间注释的示例代码。如何改进代码?
这发生在施工时:
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