Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy DataContract is faster than Serializable?
    text
    copied!<p>I tried to make the serialization and deserialization of a custom object using the code below.</p> <pre><code>[Serializable] public class TaskProperty { public int Id { get; set; } public DateTime ScheduleTime { get; set; } public TimeSpan InitializationTime { get; set; } public Nullable&lt;DateTime&gt; 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); </code></pre> <p>If the <code>TaskProperty</code> class is decorated with <code>DataContract</code> attribute (and with <code>DataMember</code> attribute for each property), the deserialization is much faster than when it is decorated with <code>Serializable</code> attribute:</p> <ul> <li>using <code>DataContract</code> and <code>DataMember</code> attributes, the deserialization is almost immediate;</li> <li>using <code>Serializable</code> attribute, the deserialization is very slow (it takes about 30 seconds).</li> </ul> <p>Why?</p> <p><strong>UPDATE...</strong> 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.</p> <p><strong>UPDATE 2...</strong> For completeness, I added the custom class that should be serialized and deserialized.</p> <p><strong>UPDATE 3...</strong> Well, maybe I discovered the cause of the slowness that affects the <code>Serializable</code> 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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload