⚡ System.Text.Json = Performance
JSON serialization is everywhere. System.Text.Json vs Newtonsoft.Json performance comparison.
📝 Serialization Performance
[MemoryDiagnoser]
public class JsonSerializationBenchmark
{
private readonly User _user = new User
{
Id = 1,
Name = "John Doe",
Email = "john@example.com",
CreatedAt = DateTime.UtcNow,
Roles = new[] { "Admin", "User" }
};
[Benchmark]
public string SystemTextJson_Serialize()
{
return JsonSerializer.Serialize(_user);
}
[Benchmark]
public string Newtonsoft_Serialize()
{
return JsonConvert.SerializeObject(_user);
}
[Benchmark]
public User SystemTextJson_Deserialize()
{
var json = JsonSerializer.Serialize(_user);
return JsonSerializer.Deserialize(json);
}
[Benchmark]
public User Newtonsoft_Deserialize()
{
var json = JsonConvert.SerializeObject(_user);
return JsonConvert.DeserializeObject(json);
}
}
// Results typically show:
// System.Text.Json: ~2x faster
// System.Text.Json: ~1.5x less memory
// Migration Tips
// 1. Update attributes
[JsonPropertyName("userName")]
public string UserName { get; set; }
// 2. Use JsonSerializerOptions
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
// 3. Custom Converters
public class DateTimeConverter : JsonConverter
{
public override DateTime Read(...) { }
public override void Write(...) { }
}
✅ Performance Comparison
- ✓ System.Text.Json is faster
- ✓ Less memory allocation
- ✓ Better web API performance
- ✓ Built-in .NET Core support
- ✓ Smaller package size
System.Text.Json is the future of JSON serialization in .NET. It offers superior performance and modern features.
