-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add ParseValue methods to JsonElement #42755
Comments
I am not sure what types of optimizations and avoiding allocations you are referring to here. If the primary purpose of this is as an optimization for the serializer, consider starting with an internal-only API. In the meantime, is there any reason to make it public? cc @bartonjs |
Please see the PR.
Two reasons:
|
We already have this API:
Can you point me to where in your linked PR the dependency on S.Linq.E is getting introduced? I am surprised by this and would like to understand why we have it. |
Yep. Thanks. Updated description. For S.Linq.E dependency, that is part of supporting the "dynamic" functionality that we want in 6.0. For 5.0 I have a PR out as a code example: #42097 which would leverage the proposed |
namespace System.Text.Json
{
public partial struct JsonElement
{
public static JsonElement ParseValue(ref Utf8JsonReader reader);
public static bool TryParseValue(ref Utf8JsonReader reader, [NotNullWhen(true)] out JsonElement? element);
}
} |
Background and Motivation
The
System.Text.Json.JsonElement
is intended to be obtained from a parentJsonDocument
which contains a binary "database" and creates the elements from the database as the document is navigated. When the document is done being used, the Dispose method is called to release the pooled memory allocated for the database.This works fine when the caller can use the Dispose pattern, however there are cases where Dispose can't be used including usages by the deserializer where property or element types of
System.Object
create a JsonElement (since the actual type isn't known) and assign it to the property\element.So to work around the Dispose issue, the serializer does this:
This is not intuitive and is slow since the document and element have no hint that the Dispose pattern is not needed and can't apply optimizations such as avoiding some unnecessary allocs and adding caching for literal values True, False and Null.
Proposed API
Currently there are no "Parse" methods on JsonElement (must go through JsonDocument). So this exposes a ParseValue method that can have optimizations applied. Also, since JsonElement does not implement the Dispose pattern, the usage and memory behavior is more intuitive.
No other Parse overloads are provided here since the known scenarios only include the serializer. Here's some possible additions based on JsonDocument:
Usage Examples
The serializer would use it like:
The text was updated successfully, but these errors were encountered: