JsonSerializer.Serialize优化,重用 JsonSerializerOptions 实例
文章参考自微软官方文档
地址:https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/system-text-json-configure-options?pivots=dotnet-6-0
测试代码
1 using System.Diagnostics; 2 using System.Text.Json; 3 4 static void Serialize(Forecast forecast, JsonSerializerOptions? options = null) 5 { 6 _ = JsonSerializer.Serialize( 7 forecast, 8 options ?? new JsonSerializerOptions() { WriteIndented = true }); 9 } 10 11 Forecast forecast = new(DateTime.Now, 40, "Hot"); 12 JsonSerializerOptions options = new() { WriteIndented = true }; 13 int iterations = 1000; 14 15 var watch = Stopwatch.StartNew(); 16 for (var i = 0; i < iterations; i++) 17 { 18 Serialize(forecast, options); 19 } 20 21 watch.Stop(); 22 Console.WriteLine($"重复使用一个选项实例的运行时间:{watch.ElapsedMilliseconds}"); 23 24 watch = Stopwatch.StartNew(); 25 for (int i = 0; i < iterations; i++) 26 { 27 Serialize(forecast); 28 } 29 30 watch.Stop(); 31 Console.WriteLine($"创建新选项实例所用的时间:{watch.ElapsedMilliseconds}"); 32 33 public record Forecast(DateTime Date, int TemperatureC, string Summary);
食用方法:NET6新建一个控制台项目 粘贴进去
结论
不要在每次使用时都创建新的 JsonSerializerOptions 实例。 对每个调用重复使用同一实例。