Skip to content

Instantly share code, notes, and snippets.

@eiriktsarpalis
Last active June 19, 2024 21:17
JsonValue Benchmarks
using BenchmarkDotNet.Attributes;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Benchmarks;
[HideColumns("Job", "Error", "StdDev", "RatioSD")]
[MemoryDiagnoser(displayGenColumns: false)]
public class JsonValueBenchmarks
{
private readonly JsonNode _largeObject;
private readonly JsonNode _largeObjectJsonElement;
private readonly JsonNode[] _smallValues;
private readonly JsonNode[] _smallValuesJsonElement;
public JsonValueBenchmarks()
{
_largeObject = new JsonObject()
{
["key1"] = 42,
["key2"] = "string",
["key3"] = new JsonArray() { true, 3.14159, "hello", DateTimeOffset.Now },
["key4"] = new JsonObject()
{
["key5"] = 42,
["key6"] = "string",
["key7"] = new JsonArray() { true, 3.14159, "hello", Guid.Empty },
}
};
_smallValues = [42, "I am a string", false, DateTimeOffset.Now];
_largeObjectJsonElement = JsonSerializer.Deserialize<JsonNode>(JsonSerializer.Serialize(_largeObject))!;
_smallValuesJsonElement = JsonSerializer.Deserialize<JsonNode[]>(JsonSerializer.Serialize(_smallValues))!;
}
[Benchmark]
public bool DeepEquals() => JsonNode.DeepEquals(_largeObject, _largeObject);
[Benchmark]
public bool DeepEquals_JsonElement() => JsonNode.DeepEquals(_largeObjectJsonElement, _largeObjectJsonElement);
[Benchmark]
public JsonValueKind GetValueKind()
{
JsonValueKind result = default;
foreach (JsonNode value in _smallValues.AsSpan())
{
result = value.GetValueKind();
}
return result;
}
[Benchmark]
public JsonValueKind GetValueKind_JsonElement()
{
JsonValueKind result = default;
foreach (JsonNode value in _smallValuesJsonElement.AsSpan())
{
result = value.GetValueKind();
}
return result;
}
}
Method Branch Mean Ratio Allocated Alloc Ratio
DeepEquals main 2,859.165 ns 1.00 4224 B 1.00
DeepEquals PR 270.130 ns 0.09 - 0.00
DeepEquals_JsonElement main 660.551 ns 1.00 328 B 1.00
DeepEquals_JsonElement PR 432.391 ns 0.65 - 0.00
GetValueKind main 612.784 ns 1.000 616 B 1.00
GetValueKind PR 5.243 ns 0.009 - 0.00
GetValueKind_JsonElement main 15.557 ns 1.00 - NA
GetValueKind_JsonElement PR 11.111 ns 0.71 - NA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment