Skip to content

Json generator should hoist property values in serialization fast-path when ignore condition on write is set #80703

@Sergio0694

Description

@Sergio0694

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions