-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Labels
area-System.Text.Jsonhelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributorstenet-performancePerformance related issuePerformance related issue
Milestone
Description
Description
Just noticed a minor missed optimization opportunity in the source generated serialization fast-path while going over some code in the Store. Consider this example where I have a model that has a property that allocates something on every read:
[JsonSerializable(typeof(MyModel))]
[JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
public partial class MyJsonContext : JsonSerializerContext
{
}
public class MyModel
{
public string SomeAllocatingProperty => $"The current time is: {DateTime.Now}";
}The serialization fast-path is currently this one:
private void MyModelSerializeHandler(global::System.Text.Json.Utf8JsonWriter writer, global::MyModel? value)
{
if (value == null)
{
writer.WriteNullValue();
return;
}
writer.WriteStartObject();
if (value.SomeAllocatingProperty != null)
{
writer.WriteString(PropName_SomeAllocatingProperty, value.SomeAllocatingProperty);
}
writer.WriteEndObject();
}Note the repeated read of value.SomeAllocatingProperty. The generator could improve this if:
- Ignore condition is to ignore null/default values on write
- The property is of a nullable or reference type
And change that branch to instead be:
PropertyType __value_SomeAllocatingProperty = value.SomeAllocatingProperty;
if ((object)__value_SomeAllocatingProperty != null)
{
writer.WriteString(PropName_SomeAllocatingProperty, __value_SomeAllocatingProperty);
}Using legacy style syntax here for backwards compat, but of course you could also use value.Prop is { } propValue and use that local.
Configuration
- System.Text.Json 7.0.1
Regression?
No.
MihaZupan and PaulusParssinen
Metadata
Metadata
Assignees
Labels
area-System.Text.Jsonhelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributorstenet-performancePerformance related issuePerformance related issue