title: Efficiency of deserialization vs. XmlReader
body: <p>I'm working with a complicated xml schema, for which I have created a class structure using xsd.exe (with some effort).  I can now reliably deserialize the xml into the generated class structure.  For example, consider the following xml from the web service:</p>
  
  <pre><code>&lt;ODM FileType="Snapshot" CreationDateTime="2009-10-09T19:58:46.5967434Z" ODMVersion="1.3.0" SourceSystem="XXX" SourceSystemVersion="999"&gt;
    &lt;Study OID="2"&gt;
      &lt;GlobalVariables&gt;
        &lt;StudyName&gt;Test1&lt;/StudyName&gt;
        &lt;StudyDescription/&gt;
        &lt;ProtocolName&gt;Test0001&lt;/ProtocolName&gt;
      &lt;/GlobalVariables&gt;
      &lt;MetaDataVersion OID="1" Name="Base Version" Description=""/&gt;
      &lt;MetaDataVersion OID="2" Name="Test0001" Description=""/&gt;
      &lt;MetaDataVersion OID="3" Name="Test0002" Description=""/&gt;
    &lt;/Study&gt;
  &lt;/ODM&gt;
  </code></pre>
  
  <p>I can deserialize the xml as follows:</p>
  
  <pre><code>public ODMcomplexTypeDefinitionStudy GetStudy(string studyId)
  {
    ODMcomplexTypeDefinitionStudy study = null;
    ODM odm = Deserialize&lt;ODM&gt;(Service.GetStudy(studyId));
    if (odm.Study.Length &gt; 0)
      study = odm.Study[0];
    return study;
  }
  </code></pre>
  
  <p>Service.GetStudy() returns an HTTPResponse stream from the web service.  And Deserialize() is a helper method that deserializes the stream into the object type T.  </p>
  
  <p>My question is this: is it more efficient to let the deserialization process create the entire class structure and deserialize the xml, or is it more efficient to grab only the xml of interest and deserialize that xml.  For example, I could replace the above code with:</p>
  
  <pre><code>public ODMcomplexTypeDefinitionStudy GetStudy(string studyId)
  {
    ODMcomplexTypeDefinitionStudy study = null;
    using (XmlReader reader = XmlReader.Create(Service.GetStudy(studyId)))
    {
      XDocument xdoc = XDocument.Load(reader);
      XNamespace odmns = xdoc.Root.Name.Namespace;
      XElement elStudy = xdoc.Root.Element(odmns + "Study");
      study = Deserialize&lt;ODMcomplexTypeDefinitionStudy&gt;(elStudy.ToString());
    }
  return study;
  }
  </code></pre>
  
  <p>I suspect that the first approach is preferred -- there is a lot of dom manipulation going on in the second example, and the deserialization process must have optimizations; however, what happens when the xml grows dramatically?  Let's say the source returns 1 MB of xml and I'm really only interested in a very small component of that xml.  Should I let the deserialzation process fill up the containing ODM class with all it's arrays and properties of child nodes?  Or just go get the child node as in the second example!!??</p>
  
  <p>Not sure this helps, but here's a summary image of the dilemma:</p>
  
  <p><img src="https://farm3.static.flickr.com/2631/4004603153_25989c820f_o.png" alt="alt text"></p>