-5

I'm using the .NET Framework 4.7.2.

Stopwatch sw = new Stopwatch();
sw.Start();

JsonDocument jdoc = JsonDocument.Parse("{\"a\":123456789}");
JsonElement test = jdoc.RootElement.GetProperty("a");

sw.Stop();

Console.WriteLine(test + $" ({sw.ElapsedMilliseconds}ms)");

It prints out 123456789 (39ms). I'm getting an average of 40ms. What's going on? Why is this so much slower than JavaScript's JSON.parse?

killaz
  • 37
  • 1
  • 8
  • 2 things: in that old version of ASP.NET there might be a static generic method you can call that parses that string into an object, like System.Text.Json.Serializer.Deserialize>(someString). It may be faster. I do know that such a method exists in ASP.NET Core. I recommend you move to ASP.NET 7 as Microsoft has greatly optimized the JSON methods since 4.7.2 – user3163495 Aug 29 '23 at 00:56
  • 2
    [This article](https://dotnetcoretutorials.com/what-those-benchmarks-of-system-text-json-dont-mention/?expand_article=1) I found by googling says it is around 1.538 ms. – Orifjon Aug 29 '23 at 00:59
  • 3
    You need to learn how to do benchmarking. You're picking up the time it takes to load the System.Text.Json assembly and then to JIT all the functions involved in parsing JSON. At the very least, do it once (or a few times, in a loop) to _warm_ things up, then start the timer. Inside the timer put the call in a loop, doing the operation (say) 1000 times to smooth things out – Flydog57 Aug 29 '23 at 02:23
  • 1
    You should take a look at Eric Lippert's 4-part series on benchmarking mistakes ([one](https://ericlippert.com/2013/05/14/benchmarking-mistakes-part-one/), [two](https://ericlippert.com/2013/05/21/benchmarking-mistakes-part-two/), [three](https://ericlippert.com/2013/07/09/benchmarking-mistakes-part-three/), [four](https://ericlippert.com/2013/08/19/benchmarking-mistakes-part-four/)) to make sure your measurements are really valid. His [performance rant](https://ericlippert.com/2012/12/17/performance-rant/) is also worth a read. – dbc Aug 29 '23 at 05:18
  • 1
    By the way, `JsonDocument` is disposable, and needs to be disposed to release pooled memory back to the system. – dbc Aug 29 '23 at 06:12

0 Answers0