I tried to make the serialization and deserialization of a custom object using the code below.
[Serializable]
public class TaskProperty
{
public int Id { get; set; }
public DateTime ScheduleTime { get; set; }
public TimeSpan InitializationTime { get; set; }
public Nullable<DateTime> InstantOfStart { get; set; }
public TimeSpan TotalElapsedTime { get; set; }
}
// Main
var serializer = new DataContractSerializer(typeof(TaskProperty));
var reader = new FileStream("myfile.xml", FileMode.Open);
TaskProperty deserialized = (TaskProperty)(serializer.ReadObject(reader));
reader.Close();
Console.WriteLine("deserialized: {0}", deserialized);
If the TaskProperty
class is decorated with DataContract
attribute (and with DataMember
attribute for each property), the deserialization is much faster than when it is decorated with Serializable
attribute:
- using
DataContract
andDataMember
attributes, the deserialization is almost immediate; - using
Serializable
attribute, the deserialization is very slow (it takes about 30 seconds).
Why?
UPDATE... Furthermore, if the deserialization is preceded by the serialization of an object of the same type (obviously with different contents), the serialization is slow while the deserialization is fast. In a similar way, if serialization is preceded by deserializing an object of the same type, the deserialization is slow while the serialization is fast.
UPDATE 2... For completeness, I added the custom class that should be serialized and deserialized.
UPDATE 3... Well, maybe I discovered the cause of the slowness that affects the Serializable
attribute, but I do not understand why. Essentially, if I explicitly declare the five private fields related to the five properties, as a consequence, the first serialization (or deserialization) is almost instant. Why?