title: How to make XML deserialization faster?
body: <p>I have the following piece of code</p>
  
  <pre><code>public static object XmlDeserialize(string xml, Type objType)
  {
      StringReader stream = null;
      XmlTextReader reader = null;
      try
      {
          XmlSerializer serializer = new XmlSerializer(objType);
          stream = new StringReader(xml); // Read xml data
          reader = new XmlTextReader(stream);  // Create reader
          return serializer.Deserialize(reader);
      }
      finally
      {
          if(stream != null) stream.Close();
          if(reader != null) reader.Close();
      }
  }
  </code></pre>
  
  <p>The object itself has been generated via xsd.exe and looks kind of like this:</p>
  
  <pre><code>/// &lt;remarks/&gt;
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
  [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
  public partial class MyObject {
  
      private DemographicsCriteriaStateStartAge[] startAgesField;
  
      private DemographicsCriteriaStateEndAge[] endAgesField;
  
      private DemographicsCriteriaStateFilter[] selectedFiltersField;
  
      /// &lt;remarks/&gt;
      [System.Xml.Serialization.XmlArrayItemAttribute("StartAge", IsNullable=false)]
      public DemographicsCriteriaStateStartAge[] StartAges {
          get {
              return this.startAgesField;
          }
          set {
              this.startAgesField = value;
          }
      }
      ...
  </code></pre>
  
  <p>The method is typically called like this:</p>
  
  <pre><code>var obj = (MyObject) XmlDeserialize(someXmlString, typeof(MyObject));
  </code></pre>
  
  <p>The following line of code always take a pretty large chunk of time (compared to everything else):</p>
  
  <pre><code>XmlSerializer serializer = new XmlSerializer(objType);
  </code></pre>
  
  <p>What is going on here, e.g. is it compiling a deserialization assembly in the background?  Why the performance issue?</p>
  
  <p>What can I do to ameliorate this performance problem?</p>