2010-09-02 56 views
4

當我嘗試從XML文件執行加載時,我感覺xstream加載速度達不到我的要求。對於 帶有10k ++條目的「數據庫」,它將需要幾分鐘的時間。優化xstream的加載速度

以下是我用來序列化的整個數據結構。列表大小(符號和代碼)將爲 大約10k ++條目。

http://jstock.cvs.sourceforge.net/viewvc/jstock/jstock/src/org/yccheok/jstock/engine/StockCodeAndSymbolDatabase.java?revision=1.11&view=markup

有什麼辦法,我可以嘗試一下,看看它是否會加速我的加載時間?能夠仍然加載回去 以前保存的文件也很重要。

以下是用於反序列化的代碼。謝謝。

@SuppressWarnings("unchecked") 
public static <A> A fromXML(Class c, File file) { 
    XStream xStream = new XStream(new DomDriver("UTF-8")); 
    InputStream inputStream = null; 

    try { 
     inputStream = new java.io.FileInputStream(file); 
     Object object = xStream.fromXML(inputStream); 
     if (c.isInstance(object)) { 
      return (A)object; 
     } 
    } 
    catch (Exception exp) { 
     log.error(null, exp); 
    } 
    finally { 
     if (false == close(inputStream)) { 
     return null; 
     } 
     inputStream = null; 
    } 

    return null; 
} 

回答

6

避免使用緩慢的DomDriver。

@SuppressWarnings("unchecked") 
public static <A> A fromXML(Class c, File file) { 
    // Don't ever try to use DomDriver. They are VERY slow. 
    XStream xStream = new XStream(); 
    InputStream inputStream = null; 
    Reader reader = null; 

    try { 
     inputStream = new java.io.FileInputStream(file); 
     reader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); 
     Object object = xStream.fromXML(reader); 

     if (c.isInstance(object)) { 
      return (A)object; 
     } 
    } 
    catch (Exception exp) { 
     log.error(null, exp); 
    } 
    finally { 
     if (false == close(reader)) { 
      return null; 
     } 
     if (false == close(inputStream)) { 
      return null; 
     } 
     reader = null; 
     inputStream = null; 
    } 

    return null; 
}