2011-11-27 72 views
3

我的代碼太慢了,但我不確定如何改進它。從磁盤讀取到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 
+0

可能與http://stackoverflow.com/questio相關ns/6340802/java -xpath-apache-jaxp-implementation-performance –

+0

切換到VTD-XML <您的問題將消失 –

回答

3

你可能會從這個問題,我記錄在這裏的痛苦:

Java XPath (Apache JAXP implementation) performance

從本質上講,你要添加這些JVM參數在很大程度上加快Xalan的XPath實現:

-Dorg.apache.xml.dtm.DTMManager= 
    org.apache.xml.dtm.ref.DTMManagerDefault 

-Dcom.sun.org.apache.xml.internal.dtm.DTMManager= 
    com.sun.org.apache.xml.internal.dtm.ref.DTMManagerDefault 
4

你應該預先編譯XPath表達式到XPathExpression,使用XPath.compile。然後致電XPathExpression.evaluate

如果您多次執行它,這將節省您的時間。我假設情況是這樣,或20毫秒應該不重要。

編輯:正如在評論中提到的,這question有進一步的信息,包括一個JVM參數。

+0

我將所有內容都更改爲預編譯表達式,但它並未真正提升性能,可能只有幾ms。有沒有更快的方法來構建dom或更快的xPath評估器? –

+0

@Franz,所以它只需要將近20毫秒來評估一個以前編譯的表達式?你正在使用哪個實現(我認爲'getClass'會告訴你)?這[問題](http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-implementation-performance)表明Xalan 2.7.1是最快的(測試過的),並且提供了用於優化的JVM參數。 –

+0

該示例將更新您的想法。 –