title: Performance optimizing use of generated XmlSerializer class
body: <p>We have a few XML files that are being read by our applications. The XML format is fixed, and thus we can read them very easily with <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx" rel="nofollow noreferrer">XmlSerializer</a>.</p>
  
  <p>I use this code to read the XML files and convert them to classes:</p>
  
  <pre><code>public static T FromXml&lt;T&gt;(this string xml) where T : class
  {
      if (string.IsNullOrEmpty(xml))
      {
          return default(T);
      }
  
      XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
  
      XmlTextReader textReader = new XmlTextReader(new StringReader(xml));
      textReader.Normalization = false;
  
      XmlReaderSettings settings = new XmlReaderSettings();
  
      T value;
  
      using (XmlReader reader = XmlReader.Create(textReader, settings))
      {
          value = (T)xmlserializer.Deserialize(reader);
      }
  
      return value;
  }
  </code></pre>
  
  <p>However, there are some performance issues. When calling this code for the first time a specific type for <code>T</code> is used, the <code>XmlSerializer</code> generates a <code>Project.XmlSerializer.dll</code> file.</p>
  
  <p>This is fine, but costs some precious milliseconds (about 900ms in my case). This can be circumvented by generating that assembly on forehand, using the <a href="http://msdn.microsoft.com/en-us/library/bk3w6240(v=vs.110).aspx" rel="nofollow noreferrer">XML Serializer Generator (sgen)</a>. This brings down the time to about half. Primarily due to the reading and reflection of the assembly.</p>
  
  <p>I want to <strong>optimize this further, by bringing the <code>XmlSerializer</code> classes inside the assembly the actual classes are in</strong>, but I can't find a way to let <code>XmlSerializer</code> know not to read an external assembly, but use the serializer from the current assembly.</p>
  
  <p>Any thoughts how to do this or an alternative way to make this work? (I can't pre-load them since most of the serialized classes are used at start-up)</p>
  
  <hr>
  
  <p>The analysis using ANTS Profiler (metrics from other machine, but same pattern):</p>
  
  <p><img src="https://i.stack.imgur.com/QWlob.png" alt="enter image description here"></p>
  
  <p>Plain. Most of the time (300ms + 400ms = 700ms) is lost in generating and loading the XmlSerializer assembly.</p>
  
  <p><img src="https://i.stack.imgur.com/1zh8a.png" alt="enter image description here"></p>
  
  <p>With sgen generated assembly. Most of the time (336ms) is lost in loading the XmlSerializer assembly.</p>
  
  <p><img src="https://i.stack.imgur.com/mGgbe.png" alt="enter image description here"></p>
  
  <p>When including the actual source of the assembly inside the project, and calling the serializer directly, the action goes down to 456ms (was 1s in first, 556ms in second).</p>