我的代码太慢了,但我不确定如何改进它。从磁盘读取 1k 文件到 DOM 大约需要 20 毫秒,这可能取决于磁盘的情况而可以接受,但接下来对 xpath 语句进行处理需要另外 20 毫秒,这是远远太长的时间。以下是一些带有时间注释的示例代码,请问如何改进代码?
这发生在构建时:
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