How to improve Serialize performance (1)

  • 1472
  • 0
  • C#
  • 2013-08-20

摘要:How to Import Serialize performance (1)

筆者常聽到許多人對序列化的卻步在於序列化產生的成本很高 ,
 
因此來撰寫有關增進序列化效能的一些建議 , 
 
序列化會遞迴一個 class 所有的屬性和描述並將之寫出 binary data , 
 
當一個 class 屬性越多 , 因為描述所產生的 binary data也會越多 , 而反序列化時 , 也需要相對的時間 , 
 
因此我們可以考慮當屬性值 為 Null 時 , 選擇不用輸出這個屬性 , 或者有些不必要輸出的屬性 , 
 
也可以考慮不必輸出  , 不但減少產出的 size ,  在序列化 / 反序列化也能獲得一點回饋 .
 
標記特定屬性不序列化 :
 
People holmes = new People{
                  id = "test",
                  pwd = "123"
                  };

 using(MemoryStream ms = new MemoryStream()){
                
                 BinaryFormatter bf = new BinaryFormatter();
                 bf.Serialize(ms,holmes);

                 byte[] result = ms.ToArray();

                 foreach (var byteData in result){
                    Response.Write(byteData);
                 }
}

[Serializable]
public class People
{
    public string _id;
    public string _pwd;
    public string _sex;
    public string _age;

    public string id
    {
        get { return this._id; }
        set { this._id = value; }
    }

    
    public string pwd
    {
        get { return this._pwd; }
        set { this._pwd = value; }
    }

    public string sex
    {
        get { return this._sex; }
        set { this._sex = value; }
    }

    public string age
    {
        get { return this._age; }
        set { this._age = value; }
    }
    public People() { }
}

 

以上程式碼產出的 size 為 329 個位元組 , 當我們將 id 標記為 [NonSerialized] , Size 便降到 301 個位元組
 
例如 Xml Serializer 也提供了 XmlIgnore 標記 , 當屬性值為 Null 時 , 則不輸出 :
 
Product p = new  Product(){
            ProductID = 123,
            ProductName = "test"
             };
    
using (TextWriter tw = new StreamWriter("C:\\test2.bin")) {

            XmlSerializer xs = new XmlSerializer(typeof(Product));
            xs.Serialize(tw, p);
 };


[XmlRoot("產品")]
public class Product{
   
    [XmlElement("產品編號")]
    public int ProductID;
    [XmlAttribute("產品名稱")]
    public string ProductName;
}

 

產出的檔案 size 為 214 個位元組 , 若將 ProductID 標記成 XmlIgnore , 則產出的 size 變成 169 個位元組