Search code examples
.netc#-4.0xmlserializersgen

XmlSerializer.Serialize takes a long time... why?


Given the following code from RssToolkit in RssXmlHelper.cs:

    /// <summary>
    /// Returns XML of the Generic Type.
    /// </summary>
    /// <param name="rssDocument">The RSS document.</param>
    /// <typeparam name="T">RssDocumentBase</typeparam>
    /// <returns>string</returns>
    public static string ToRssXml<T>(T rssDocument) where T : RssDocumentBase
    {
        if (rssDocument == null)
        {
            throw new ArgumentNullException("rssDocument");
        }

        using (StringWriter output = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(output, rssDocument);
            return output.ToString();
        }
    }

When serializer.Serialize() is called in my WCF service, it takes a whole lot of time.

I have this sitting in a WCF service that I call from my project. I step into it, and sure enough, that's the problem point.

I then reference the project within my solution, and no problem.

Is there something I should be doing differently when using this in a WCF service?

-- UPDATE --

Ok, so I installed Microsoft Windows SDK for Windows 7 and .NET Framework 4, ran sgne.exe RssToolkit.dll and get the following error:

Error:  An attempt was made to load an assembly with in incorrect format [path to rsstoolkit.dll]
- Could not load file or assemply [path to rsstoolkit.dll] or one of its dependencies.  This assembly was build by a runtime newer than the currently loaded runtime and cannot be loaded.

The target framework for my RssToolkit project is set to 4.0, matching the Windows SDK for .Net 4. Is that not correct?


Solution

  • You could generate serialization assemblies using sgen.exe, the XML Serializer Generator Tool that comes with the Windows SDK. I've seen drastic improvements by using it on large classes.

    It basically will generate code that knows how to serialize and deserialize every one of the objects you have in your domain. Once you have generated the DLL, you can include it in your project as an assembly reference, and then use the classes within it instead of the XmlSerializer you're using now.