2

I need to minimalize size of serialized class. As I understand size of serialized data depends on names of properties.
So class

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

is smaller after serialization than

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

Is there a way to mimimalize size of second class without changing names of properties to shorter versions like in first example? I need this to store data in Server.Cache so it is binary serialization.

Marek Kwiendacz
  • 9,524
  • 14
  • 48
  • 72

2 Answers2

3

If you are using XML Serialisation, yes you can:

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

if it is a binary serialization, there is no need for it.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
  • re your last line; that isn't quite true, or rather: it depends on the serializer. protobuf won't care, but BinaryFormatter uses field-names, and field-names *generally* depend on property-names, especially for automatically implemented properties. – Marc Gravell Mar 13 '11 at 19:32
3

If size is your aim, something terse like protobuf would be good; consider some measures: Performance Tests of Serializations used by WCF Bindings

In your case, using protobuf-net:

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

The size doesn't depend on the member-names, it is pure-binary, there are no text overheads, and it uses efficient encodings for most data types. Example usage:

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

In fact, the above type will be somewhere between 2 and 6 bytes, depending on the value of the property (integers close to 0 take less space).

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900