'Does string.AsSpan() prevent string allocation?
I am building a custom JsonConverter, and i was wondering about the behavior of AsSpan().
public override int Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
{
return int.TryParse(Encoding.UTF8.GetString(reader.ValueSpan).AsSpan(),
System.Globalization.NumberStyles.Integer | System.Globalization.NumberStyles.AllowThousands,
System.Globalization.CultureInfo.InvariantCulture,
out int value) ? value : default;
}
Since Encoding.Utf8.GetString(...) returns a string, then AsSpan() is called, does that mean that first a string is allocated on the heap, then a span is built from it ? Or does the AsSpan() method "blocks" the string allocation and directly make it into a span ?
Thank you for the clarification
Solution 1:[1]
You will have string allocation inside GetString.
Let's see the source of GetString - it calls CreateStringFromEncoding inside it.
CreateStringFromEncoding then calls FastAllocateString which is actually allocating memory (see here)
So, span-based GetString is able to prevent creation and allocation of intermediate byte array for input data in case you have such a data in some other representation (for example, as of int array or something else), but does not prevent allocation of output string object.
The AsSpan call do not affects GetString in any way, and in this particular case with int.Parse if totally useless, as the int.Parse already has overload which takes string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
