2017-07-27 92 views
-1

我做了一個WPF應用程序,它使用trie(基於this one)來存儲波蘭語詞典(37.9MB)。從dictionary.txt創建它需要很多時間(我的筆記本電腦上需要30秒)。如何保存/加載在c#中創建的trie樹WPF

我想,也許如果我創建了一種已經完成的trie的二進制文件,並加載它,它會加快速度。

回答

0

您可以嘗試將其保存爲序列化對象,無論是XML還是二進制。您需要標記將用該屬性序列化的類。通用集合已經可序列化。

[Serializable] 
public class Node 
{ 
... 
} 

[Serializable] 
public class Trie 
{ 
... 
} 

XML保存

var trie = new Trie(); 

using (var fs = new System.IO.FileStream("path", FileMode.CreateNew, FileAccess.Write, FileShare.None)) 
{ 
    Type objType = typeof (Trie); 
    var xmls = new XmlSerializer(objType); 

    xmls.Serialize(fs, trie); 
} 

XML負載

XmlSerializer xmls = new XmlSerializer(typeof(Trie)); 
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) 
    return xmls.Deserialize(fs) as Trie; 

二進制保存

var trie = new Trie(); 
using (var fs = new System.IO.FileStream("path", FileMode.CreateNew, 
FileAccess.Write)) 
{ 
    var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
    bf.Serialize(fs, trie); 
} 

二進制負載

using (var fs = new FileStream("Path", FileMode.Open, FileAccess.Read)) 
{ 
     var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
     return bf.Deserialize(fs) as Trie; 
} 
+0

兩者有什麼區別?這些解決方案如何(不)便攜?如果我製作我的應用程序的發佈版本,它是否可以在所有Windows(使用.NET)上運行? – Jecke

+0

所以,我的序列化經驗是XML在程序版本之間更安全,但二進制更快,並且很可能導致文件更小。當使用二進制序列化文件時,它與類的版本很相關,程序可以更新,但更改序列化類通常會打破加載文件的能力,除非您自己實現ISerializable並執行所有序列化函數。 XML在修訂版本之間更安全,但會在格式化形式的保存文件中包含大量開銷。 兩者都是便攜式的。 –

+0

我嘗試使用二進制序列化(我簡單地複製你的代碼,改變'trie'到加載波蘭語字典和''路徑''到'「dict.xml」''),我得到的文件是相當大的:54.2MB (而不是37.9MB的dictionary.txt)。我試着加載它(再次,簡單地將你的代碼修改爲'return'到'Trie my_dictionary ='),但它現在被卡住或加載了幾分鐘......我做錯了什麼或者是否還有其他問題? – Jecke