2011-03-13 87 views
1

我需要最小化序列化類的大小。據我瞭解,序列化數據的大小取決於屬性的名稱。
因此類如何最小化序列化數據的大小

class XYZ 
{ 
public int X { get;set;} 
} 

是系列化比

class XYZ 
{ 
public int NumberOfUsersWithAccessToReportingService { get;set;} 
} 

後小有沒有辦法來mimimalize第二類的大小,而不在第一個例子中更改屬性的名稱,以更短的版本是怎樣的?我需要這個在Server.Cache中存儲數據,所以它是二進制序列化。

+3

http://code.google.com/p/protobuf-net/可能是一個很好的候選 – Guillaume86 2011-03-13 18:47:30

回答

3

如果尺寸是你的目標,像protobuf這樣簡潔的東西會很好;考慮一些措施:Performance Tests of Serializations used by WCF Bindings

在你的情況下,使用protobuf網:

[ProtoContract] 
class XYZ 
{ 
    [ProtoMember(1)] 
    public int NumberOfUsersWithAccessToReportingService { get;set;} 
} 

大小並不取決於成員的名字,它是純粹的二進制,沒有文字開銷,它對大多數數據類型使用高效的編碼。實例:

using(var file = File.Create(path)) 
{ 
    Serializer.Serialize(file, obj); 
} 
... 
using(var file = File.OpenRead(path)) 
{ 
    var obj = Serializer.Deserialize<YourType>(file); 
} 

實際上,上述類型將是介於2首6個字節,這取決於屬性的值(整數接近0花費較少的空間)。

+0

你已經創建了完美的序列化器,謝謝:) – 2011-03-14 09:43:59

+0

@Korin - 公平地說,雖然我可能*實現了*,*設計*有谷歌... – 2011-03-14 11:57:23

2

如果使用XML序列化,是的,你可以:

class XYZ 
{ 
    [XmlElement("X")] 
    public int NumberOfUsersWithAccessToReportingService { get;set;} 
} 

,如果它是一個二進制序列化,就沒有必要爲它。

+0

重新您的最後一行;這是不正確的,或者更確切地說:這取決於序列化程序。 protobuf不會在意,但BinaryFormatter使用字段名和字段名*通常*取決於屬性名,特別是對於自動實現的屬性。 – 2011-03-13 19:32:53

+0

謝謝馬克。我會更新我的答案。 – Aliostad 2011-03-13 19:36:35