|
| 1 | +using BenchmarkDotNet.Attributes; |
| 2 | +using MicroBenchmarks; |
| 3 | +using System.Buffers; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Text.Json.Document.Tests; |
| 6 | +using System.Text.Json.Nodes; |
| 7 | +using System.Text.Json.Tests; |
| 8 | + |
| 9 | +namespace System.Text.Json.Node.Tests |
| 10 | +{ |
| 11 | + [BenchmarkCategory(Categories.Libraries, Categories.JSON)] |
| 12 | + public class Perf_ParseThenWrite |
| 13 | + { |
| 14 | + public enum TestCaseType |
| 15 | + { |
| 16 | + HelloWorld, |
| 17 | + DeepTree, |
| 18 | + BroadTree, |
| 19 | + LotsOfNumbers, |
| 20 | + LotsOfStrings, |
| 21 | + Json400B, |
| 22 | + Json4KB, |
| 23 | + Json400KB |
| 24 | + } |
| 25 | + |
| 26 | + private byte[] _dataUtf8; |
| 27 | + private Utf8JsonWriter _writer; |
| 28 | + |
| 29 | + [ParamsAllValues] |
| 30 | + public TestCaseType TestCase; |
| 31 | + |
| 32 | + [Params(true, false)] |
| 33 | + public bool IsDataIndented; |
| 34 | + |
| 35 | + [GlobalSetup] |
| 36 | + public void Setup() |
| 37 | + { |
| 38 | + string jsonString = JsonStrings.ResourceManager.GetString(TestCase.ToString()); |
| 39 | + |
| 40 | + if (!IsDataIndented) |
| 41 | + { |
| 42 | + _dataUtf8 = DocumentHelpers.RemoveFormatting(jsonString); |
| 43 | + } |
| 44 | + else |
| 45 | + { |
| 46 | + _dataUtf8 = Encoding.UTF8.GetBytes(jsonString); |
| 47 | + } |
| 48 | + |
| 49 | + var abw = new ArrayBufferWriter<byte>(); |
| 50 | + _writer = new Utf8JsonWriter(abw, new JsonWriterOptions { Indented = IsDataIndented }); |
| 51 | + } |
| 52 | + |
| 53 | + [GlobalCleanup] |
| 54 | + public void CleanUp() |
| 55 | + { |
| 56 | + _writer.Dispose(); |
| 57 | + } |
| 58 | + |
| 59 | + [Benchmark] |
| 60 | + public void ParseThenWrite() |
| 61 | + { |
| 62 | + _writer.Reset(); |
| 63 | + |
| 64 | + JsonNode jsonNode = JsonNode.Parse(_dataUtf8); |
| 65 | + WalkNode(jsonNode); |
| 66 | + jsonNode.WriteTo(_writer); |
| 67 | + |
| 68 | + |
| 69 | + static void WalkNode(JsonNode node) |
| 70 | + { |
| 71 | + // Forces conversion of lazy JsonElement representation of document into |
| 72 | + // a materialized JsonNode tree so that we measure writing performance |
| 73 | + // of the latter representation. |
| 74 | + |
| 75 | + switch (node) |
| 76 | + { |
| 77 | + case JsonObject obj: |
| 78 | + foreach (KeyValuePair<string, JsonNode> kvp in obj) |
| 79 | + WalkNode(kvp.Value); |
| 80 | + break; |
| 81 | + case JsonArray arr: |
| 82 | + foreach (JsonNode elem in arr) |
| 83 | + WalkNode(elem); |
| 84 | + break; |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | +} |
0 commit comments