Skip to content

[Performance] XmlSerializer instantiation on every compilation analysis #59

@mfogliatto

Description

@mfogliatto

Problem

XmlConfigurationLoader creates a new XmlSerializer(typeof(ReferenceCopConfig)) instance on every call to ParseConfigFrom(). In .NET, XmlSerializer constructors that take a single Type argument generate and compile a dynamic assembly at runtime. While the framework caches these for new XmlSerializer(type), this still incurs reflection overhead on each instantiation.

More critically, since this runs inside a Roslyn analyzer (ReferenceCopAnalyzer.InitializeRegisterCompilationAction), it executes on every compilation during IDE editing. This creates unnecessary GC pressure and CPU work in a hot path.

Affected File

src/ReferenceCop/Configuration/XmlConfigurationLoader.csParseConfigFrom() method (line ~50)

Impact

  • Medium — Adds latency to every compilation action in the IDE (Roslyn analyzers should be as fast as possible)
  • Repeated object allocation and reflection on a hot path
  • Multiplied across all projects in a solution that reference ReferenceCop

Suggested Optimization

Cache the XmlSerializer instance as a static field:

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

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

XmlSerializer is thread-safe for deserialization, so a shared static instance is safe here.

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