Skip to content

Consider adding Utf8JsonWriter support for writing raw property names #54005

Description

@layomia

#1784 discusses writing raw JSON values when using Utf8JsonWriter. We can build on top that to support writing raw property names. This could be useful when pre-generating JSON serialization logic and we know the runtime property names ahead of time.

From @Tornhoof in #1784 (comment):

As linked by @layomia for the source-gen code (#53212 (comment)) having a Raw Write functionality could be useful to replace the JsonEncodedText members with ReadOnlySpan<byte> and preencoded utf8 member names. At the moment, Benchmarks show that JsonEncodedText is faster (10-15%) for writing known property names in json as there is a fastpath for it. For the ROS overload it needs to check the validity of the bytes and possibly escaping. Having a Raw API to bypass the encoding check the performance, should be similar and would allow the source-gen to use ROS.

Benchmarks (also from #1784 (comment))

	public class JsonWriteBenchmark
	{
		private static readonly JsonEncodedText JetPropertyName = JsonEncodedText.Encode("message");

		private static ReadOnlySpan<byte> ROSPropertyName =>
			new byte[] {0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65};


		[Benchmark]
		public void WriteReadOnlySpanPropertyName()
		{
			using var ms = new MemoryStream();
			Utf8JsonWriter writer = new Utf8JsonWriter(ms);
			writer.WriteStartObject();
			writer.WriteString(ROSPropertyName, "Hello World");
			writer.WriteEndObject();
			writer.Flush();
		}

		[Benchmark]
		public void WriteJsonEncodedTextPropertyName()
		{
			using var ms = new MemoryStream();
			Utf8JsonWriter writer = new Utf8JsonWriter(ms);
			writer.WriteStartObject();
			writer.WriteString(JetPropertyName, "Hello World");
			writer.WriteEndObject();
			writer.Flush();
		}
	}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions