Skip to content

Add an analyzer that warns on single-use JsonSerializerOptions instances #65396

@eiriktsarpalis

Description

@eiriktsarpalis

Forked from #40072.

While #64646 mitigates most of the performance issues related to creating single-use JsonSerializerOptions instances, this is still a suboptimal pattern and users are better off working with singleton JsonSerializerOptions instances. We should add an analyzer that warns about any JsonSerializerOptions construction that flows only to a call to a JsonSerializer method argument.

The analyzer should warn if any of the following patterns are detected:

JsonSerializer.Serialize(value, new JsonSerializerOptions { /* some custom config */ });

or if we're passing a local that has been initialized in the same method

var options = useDefault ? JsonSerializerOptions.Default : new JsonSerializerOptions { /* some custom config */ };

foreach(object value in values)
{
    JsonSerializer.Serialize(value, options);
}

In both cases the analyzer should recommend lifting the options instance to a static variable or use DI, but would most likely not provide a fixer.

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedapi-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Text.Jsonblocking-releasecode-analyzerMarks an issue that suggests a Roslyn analyzerin-prThere is an active PR which will close this issue when it is mergedtenet-performancePerformance related issue

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions