1

In .NET 2 I have the following code, which works okay:

public static T DeserializeStream<T>(this Stream xmlStream)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    using (XmlReader xmlReader = XmlReader.Create(xmlStream))
    {
        return (T)serializer.Deserialize(xmlReader);
    }
}

however when I change the constructor to the more specific kind but fill it with blank values the code runs at least 5x slower when I run it on a large list of files of the same type:

XmlSerializer serializer = new XmlSerializer(typeof(T), null, Type.EmptyTypes, null, null);

Why is this? Is this expected? Does this stop it caching some sort of type data?

Patrick
  • 677
  • 5
  • 14
  • *Does this stop it caching some sort of type data?* -- yes, this is exactly what happens. See [this answer](https://stackoverflow.com/a/23897411/3744182) by Marc Gravell to [Memory Leak using StreamReader and XmlSerializer](https://stackoverflow.com/q/23897145/3744182): *XmlSerializer uses assembly generation, and assemblies cannot be collected. It does some automatic cache/reuse for the simplest constructor scenarios (`new XmlSerializer(Type)`, etc), but not for this scenario. Consequently, you should cache it manually* – dbc Mar 31 '23 at 03:42
  • 1
    It's also stated in the [docs](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer?redirectedfrom=MSDN&view=net-6.0#dynamically-generated-assemblies): *To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors... If you use any of the other constructors, multiple versions of the same assembly are generated...* – dbc Mar 31 '23 at 03:43
  • 1
    This was true even as far back as .NET 2. (Incidentally, are you really still using **[tag:.net-2.0]**? .NET 2 went out of support over a decade ago, in 2011.) – dbc Mar 31 '23 at 03:46
  • @dbc Ah thank you I missed that in the docs. I'm not using .NET 2 because I like it lol. Need something compatible and easily available on XP machines – Patrick Mar 31 '23 at 07:29

0 Answers0