0

I'm writing a custom json serializer based on System.Text.Json, reading utf-8 string from array. In the examples I have found a following code:

string propertyName = reader.GetString();
if (propertyName != "TypeDiscriminator") {
  throw new JsonException();
}

Surely I'm not interested in allocating propertyName variable, especially if it is such long. It will be thrown away after the name is found equal to the expected literal string.

Is there any possibility to do this check without actually getting a string instance?

J.F.
  • 13,927
  • 9
  • 27
  • 65
python_kaa
  • 1,034
  • 13
  • 27

2 Answers2

3

Use ValueTextEquals:

if (!reader.ValueTextEquals("TypeDiscriminator"))
{
    throw new JsonException();
}

For perf-critical code it can be better to translate to UTF-8 beforehand:

static readonly byte[] s_TypeDiscriminator =
    Encoding.UTF8.GetBytes("TypeDiscriminator");

if (!reader.ValueTextEquals(s_TypeDiscriminator))
{
    throw new JsonException();
}
Cory Nelson
  • 29,236
  • 5
  • 72
  • 110
0

With C# 11, you can now compare directory with a UTF-8 literal by using the u8 postfix on a string literal.

reader.ValueSpan.SequenceEqual("TypeDiscriminator"u8)

Nick Strupat
  • 4,928
  • 4
  • 44
  • 56