Thursday, December 10, 2009

Automated precompilation of xml serialized classes

To improve the performance of your code, the XmlSerializer( Type ) generates dynamic assemblies which store serialization and deserialization code of your classes.

This, however, impacts the performance as the generation takes about 300ms to complete.

.NET uses some kind of a cache to store these precompiled classes (use Reflector to inspect constructors of the class), however, a suprisingly little known SDK tool named sgen.exe can be used to actually force the precompilation. The sgen.exe invoked on Your.Assembly.dll creates Your.Assembly.XmlSerializers.dll which, if exists, is used by the XmlSerializer class.

To use the tool, create GenerateSerializers.bat in the root of your library project and put following line into it:

"c:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\sgen.exe" /force /compiler:/keyfile:key_file.snk ./bin/Debug/Your.Assembly.dll

Remeber to prepare key_file.snk with sn.exe and put it beside the GenerateSerializers.bat.

Now open your project's properties and on the Build Events tab page type following lines into the "Post-build event command line" field:

cd "$(ProjectDir)"
GenerateSerializers.bat

That's all. Your.Assembly.XmlSerializers.dll will be rebuilt whenever you rebuild project with Your.Assembly.dll.

What's more - Your.Assembly.XmlSerializers.dll will be automatically copied to other projects in the same solution which reference Your.Assembly.dll. It means that you do not have to include or reference Your.Assembly.XmlSerializers.dll anywhere in your project.

No comments: