JSON serialization refactoring and optimization #1506
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
toJSON
methods. If you specify a spacer to beautify your generated JSONs, the serializer will take a little bit more time (see the table below), but still be faster compared to the previous revision.Optimization
So long story short, the JSON serializer now uses a two
StringBuilder
for the complete operation instead of getting new ones quite often during the execution. One is used to build the JSON string itself and a second small one gets used when numbers get serialized.The behavior of the serializer hasn't changed. The generated output will be the same as before.
Benchmarks
Setup
Like the in JSON.parse optimization process, I used several JSON files to measure the performance differences. Before executing the Benchmark, these JSON files are deserialized using the Jint JsonParser and then serialized back inside the benchmark method body. The benchmarks body basically looks like like this:
This time, I benched two calls: one without any spacer defined and one with spacer-value (
serializer.Serialize(_toSerialize, JsValue.Undefined, new JsString(" "));
)These are the JSON-files used for the benchmarks
The JSON files for the test have a size between 2.7KB and 43.3MB (UTF-8 encoded).
Results
As like before, the table is huge. The relevant columns are "Ratio" and "Alloc Ratio".
OldSerializerFormatted
is the previous serializer, executed with two spaces for thespace
parameterOldSerializerUnformatted
is the previous serializer, executed without any spacerNewSerializerXYZ
is the same, but the new code