How fast is XmlSerializer?
Note: this entry has moved.
Have you ever wondered how does the
XmlSerializer
really works? Well, it
creates a temporary assembly that is built by reflecting the
type you pass to the constructor. Wait! Don't panic because
of the "reflecting" word!
It does so only once per
type, and it builds an extremely efficient pair of
Reader/Writer classes that will handle serialization/
deserialization during the life of the AppDomain.
These classes inherit the public
XmlSerializationReader and
XmlSerializationWriter classes in the
System.Xml.Serialization namespace. If you want
to take a look at the generated code, add the following
setting to the application configuration file (web.config
for a web application):
<system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="4"/>
</switches>
</system.diagnostics>
Now the serializer won't delete the temporary files
generated in the process. For a web application, the files
will be located in
C:\Documents and Settings\[YourMachineName]\ASPNET\Local
Settings\Temp, otherwise, they will be located in your current user
Local Settings\Temp folder.
You will see code that is exactly what you would have to do
if you wanted to efficiently load Xml in .NET: use nested
while/if as you read, use XmlReader methods to move down the
stream, etc. All the ugly code is there to make it really
fast.
Special thanks to Chris Sells for his XmlSerializerCompiler utility.