Skip to content

Instantly share code, notes, and snippets.

@emonarafat
Created July 3, 2025 11:53
Show Gist options
  • Select an option

  • Save emonarafat/8462435f88c41e1041b61d0cdb82c326 to your computer and use it in GitHub Desktop.

Select an option

Save emonarafat/8462435f88c41e1041b61d0cdb82c326 to your computer and use it in GitHub Desktop.
A benchmark comparison of System.Text.Json and Newtonsoft.Json in .NET
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
public class JsonSerializerComparison
{
public static void Compare(MyModel model)
{
Console.WriteLine("\n=== Benchmark: System.Text.Json ===");
var stjOpts = new JsonSerializerOptions {
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false
};
var sw = Stopwatch.StartNew();
string stjJson = JsonSerializer.Serialize(model, stjOpts);
sw.Stop();
Console.WriteLine($"System.Text.Json length: {stjJson.Length}, time: {sw.ElapsedMilliseconds}ms");
sw.Restart();
var deserializedSTJ = JsonSerializer.Deserialize<MyModel>(stjJson, stjOpts);
sw.Stop();
Console.WriteLine($"System.Text.Json deserialization time: {sw.ElapsedMilliseconds}ms");
Console.WriteLine("\n=== Benchmark: Newtonsoft.Json ===");
sw.Restart();
string newtonJson = JsonConvert.SerializeObject(model, Formatting.None);
sw.Stop();
Console.WriteLine($"Newtonsoft.Json length: {newtonJson.Length}, time: {sw.ElapsedMilliseconds}ms");
sw.Restart();
var jObject = JObject.Parse(newtonJson);
sw.Stop();
Console.WriteLine($"Newtonsoft.Json parsing (JObject) time: {sw.ElapsedMilliseconds}ms");
Console.WriteLine($"Newtonsoft JObject properties count: {jObject.Properties().Count()}");
}
public static void Main()
{
var model = new MyModel
{
Id = Guid.NewGuid(),
Name = "Test User",
Tags = new List<string> { "json", "benchmark", "serialization", ".net" },
Metadata = new Dictionary<string, string>
{
{ "role", "developer" },
{ "active", "true" },
{ "level", "senior" }
}
};
Compare(model);
}
}
public class MyModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<string> Tags { get; set; }
public Dictionary<string, string> Metadata { get; set; }
}
// 🧪 This gist demonstrates real-world differences in performance and output
// between System.Text.Json and Newtonsoft.Json serializers.
// Use this as a testbed to benchmark across your own data models.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment