A benchmark measures code performance to help answer questions with data. Comparisons are more useful than treating timings as universal: results can vary with the environment, so focus on how approaches perform relative to one another. section 10.0 section 10.2
Use benchmarks to support performance decisions:
- Measure before making changes, and compare approaches using their relative results. section 10.5
- Return results from benchmark methods so the compiler is less likely to remove work whose value is unused. section 10.2
Comparing JSON deserialization
A BenchmarkDotNet test compares Newtonsoft.Json and System.Text.Json using the same jokes.json input. The reported means are 657.7 μs and 285.2 μs respectively; treat these as results from that run, not universal timings. section 10.2
Listing 10.4 Benchmark comparing JSON deserialization
using BenchmarkDotNet.Attributes; #1
using Newtonsoft.Json;
using STJ = System.Text.Json; #2
namespace FirstBenchmark;
public class JsonDeserializationTest
{
private readonly string _jsonString;
public JsonDeserializationTest()
{
var reader = new StreamReader("jokes.json"); #3
_jsonString = reader.ReadToEnd();
}
[Benchmark]
public Joke[]? Newtonsoft() =>
JsonConvert.DeserializeObject<Joke[]>(_jsonString); #4
[Benchmark]
public Joke[]? SystemText() =>
STJ.JsonSerializer.Deserialize<Joke[]>(_jsonString); #5
}
See the benchmark methods that run both deserializers against the same input. section 10.2






















