Skip to content

[Performance] XmlConfigurationLoader creates new XmlSerializer on every instantiation #50

@mfogliatto

Description

@mfogliatto

Description

XmlConfigurationLoader.ParseConfigFrom() creates a new XmlSerializer(typeof(ReferenceCopConfig)) each time it's called. XmlSerializer constructors dynamically generate and compile a serialization assembly at runtime.

Affected Files

  • src/ReferenceCop/Configuration/XmlConfigurationLoader.cs (line ~48, ParseConfigFrom method)

Impact

  • Startup cost: Each new XmlSerializer() triggers runtime code generation (~50-200ms for complex types), adding latency during analyzer initialization
  • Memory leak in .NET Framework: Dynamically generated assemblies are never unloaded in .NET Framework, causing a slow memory leak if the analyzer is invoked repeatedly (e.g., in IDE real-time analysis scenarios)
  • Repeated allocation: In MSBuild/Roslyn scenarios where the analyzer initializes per-project, this compounds across the build

Suggested Optimization

Cache the serializer as a static field:

private static readonly XmlSerializer Serializer = new XmlSerializer(typeof(ReferenceCopConfig));

private static ReferenceCopConfig ParseConfigFrom(Stream stream)
{
    return (ReferenceCopConfig)Serializer.Deserialize(stream);
}

The XmlSerializer(Type) constructor is thread-safe for the simple single-type form, and the cached instance can be safely shared.

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance optimization

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions