Created
July 3, 2025 11:53
-
-
Save emonarafat/8462435f88c41e1041b61d0cdb82c326 to your computer and use it in GitHub Desktop.
A benchmark comparison of System.Text.Json and Newtonsoft.Json in .NET
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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