C# Serialization performance in System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,Newtonsoft.Json.JsonConvert and System.Text.Json.JsonSerializer.Serialize

来源:https://www.cnblogs.com/Fred1987/archive/2019/11/22/11910761.html
-Advertisement-
Play Games

using System;using System.Collections.Generic;using System.Collections;using System.IO;using System.Runtime.Serialization.Formatters.Binary;using Syst ...


In .net core 3.0

using System;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.Text;
using System.Text.Json;
using Google.Protobuf;
using System.Diagnostics;
using ConsoleApp389.Models;



namespace ConsoleApp389
{
class Program
{
static void Main(string[] args)
{
TestCostDemo();
Console.ReadLine();
}


static void TestCostDemo()
{
List<SalesOrderDetail> dataList = GetList();
StringBuilder msgBuilder = new StringBuilder();
Stopwatch sw = new Stopwatch();
//sw.Start();
//Console.WriteLine($"BinaryFormatterDemo started at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
//BinaryFormatterDemo<SalesOrderDetail>(dataList);
//sw.Stop();
//Console.WriteLine($"BinaryFormatterDemo stopped at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
//msgBuilder.AppendLine($"BinaryFormatterDemo cost {sw.ElapsedMilliseconds} milliseconds.");


sw.Restart();
Console.WriteLine($"NewtonJsonDemo started at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
NewtonJsonDemo<SalesOrderDetail>(dataList);
sw.Stop();
Console.WriteLine($"NewtonJsonDemo stopped at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
msgBuilder.AppendLine($"NewtonJsonDemo cost {sw.ElapsedMilliseconds} milliseconds.");


sw.Restart();
Console.WriteLine($"JsonSerializerDemo started at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
JsonSerializerDemo<SalesOrderDetail>(dataList);
sw.Stop();
Console.WriteLine($"JsonSerializerDemo stopped at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
msgBuilder.AppendLine($"JsonSerializerDemo cost {sw.ElapsedMilliseconds} milliseconds.");
string msg = msgBuilder.ToString();
Console.WriteLine(msg);
System.Diagnostics.Debug.WriteLine(msg);
}


static List<SalesOrderDetail> GetList()
{
using(AdventureWorks2017Context db=new AdventureWorks2017Context())
{
List<SalesOrderDetail> dataList = new List<SalesOrderDetail>(db.SalesOrderDetail);
return dataList;
}
}


static void BinaryFormatterDemo<T>(List<T> dataList)
{
using (FileStream fs = new FileStream($"{Guid.NewGuid().ToString().Substring(0,6)}.bin", FileMode.Create))
{
BinaryFormatter binFormatter = new BinaryFormatter();
try
{
binFormatter.Serialize(fs, dataList);
}
catch(SerializationException e)
{
Console.WriteLine($"BinaryFormatter serialize ex:{e.StackTrace}");
}
}
}


static void NewtonJsonDemo<T>(List<T> dataList)
{
try
{
string jsonString = JsonConvert.SerializeObject(dataList);
}
catch(SerializationException ex)
{
Console.WriteLine($"NewtonJson serialization ex :{ex.StackTrace}");
}
}


static void JsonSerializerDemo<T>(List<T> dataList)
{
try
{
string msJsonSerializerString = System.Text.Json.JsonSerializer.Serialize(dataList);
}
catch(SerializationException ex)
{
Console.WriteLine($"System.Text.Json.JsonSerializer ex:{ex.StackTrace}");
}
}



//static void GoogleProtoBufDemo<T>(List<T> dataList)
//{
// using (var file = File.Create("person.bin"))
// {
// ProtoBuf.Serializer.Serialize<T>(file, dataList);
// }
//}


}
}

 

 

In .net 4.8

 

using ConsoleApp390.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp390
{
    class Program
    {
        static void Main(string[] args)
        {
            TestCostDemo();
            Console.ReadLine();
        }

        static void TestCostDemo()
        {
            List<SalesOrderDetail> dataList = GetList();
            StringBuilder msgBuilder = new StringBuilder();
            Stopwatch sw = new Stopwatch();
            //sw.Start();
            //Console.WriteLine($"BinaryFormatterDemo started at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
            //BinaryFormatterDemo<SalesOrderDetail>(dataList);
            //sw.Stop();
            //Console.WriteLine($"BinaryFormatterDemo stopped at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
            //msgBuilder.AppendLine($"BinaryFormatterDemo cost {sw.ElapsedMilliseconds} milliseconds.");

            sw.Restart();
            Console.WriteLine($"NewtonJsonDemo started at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
            NewtonJsonDemo<SalesOrderDetail>(dataList);
            sw.Stop();
            Console.WriteLine($"NewtonJsonDemo stopped at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
            msgBuilder.AppendLine($"NewtonJsonDemo cost {sw.ElapsedMilliseconds} milliseconds.");

            sw.Restart();
            Console.WriteLine($"JsonSerializerDemo started at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
            JsonSerializerDemo<SalesOrderDetail>(dataList);
            sw.Stop();
            Console.WriteLine($"JsonSerializerDemo stopped at {DateTime.Now.ToString("yyyyMMddHHmmssffff")}");
            msgBuilder.AppendLine($"JsonSerializerDemo cost {sw.ElapsedMilliseconds} milliseconds.");
            string msg = msgBuilder.ToString();
            Console.WriteLine(msg);
            System.Diagnostics.Debug.WriteLine(msg);
        }
        static List<SalesOrderDetail> GetList()
        {
            using (AdventureWorks2017Entities db = new AdventureWorks2017Entities())
            {
                List<SalesOrderDetail> dataList = new List<SalesOrderDetail>(db.SalesOrderDetails);
                return dataList;
            }
        }
        static void BinaryFormatterDemo<T>(List<T> dataList)
        {
            using (FileStream fs = new FileStream($"{Guid.NewGuid().ToString().Substring(0, 6)}BinFormatter.dat", FileMode.Create))
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                try
                {
                    binFormatter.Serialize(fs, dataList);
                }
                catch (SerializationException e)
                {
                    Console.WriteLine($"BinaryFormatter serialize ex:{e.StackTrace}");
                }
            }
        }
        static void NewtonJsonDemo<T>(List<T> dataList)
        {
            try
            {
                string jsonString = JsonConvert.SerializeObject(dataList);
            }
            catch (SerializationException ex)
            {
                Console.WriteLine($"NewtonJson serialization ex :{ex.StackTrace}");
            }
        }
        static void JsonSerializerDemo<T>(List<T> dataList)
        {
            try
            {
                string msJsonSerializerString = System.Text.Json.JsonSerializer.Serialize(dataList);
            }
            catch (SerializationException ex)
            {
                Console.WriteLine($"System.Text.Json.JsonSerializer ex:{ex.StackTrace}");
            }
        }
    }
}

 

 Test them in program.

 
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp391
{
    class Program
    {
        static void Main(string[] args)
        {
            TestNet48Demo();
            if(IsFirstFinished)
            {
                TestCore30Demo();
            }
        }

        static bool IsBusy= false;

        static bool IsFirstFinished = false;
        static  void TestNet48Demo()
        {
            for (int i = 0; i < 10; i++)
            {
                if (!IsBusy)
                {
                    Console.WriteLine($"Test Net48Demo() {i}");
                    IsBusy = true;
                    Thread thread = new Thread(() =>
                      {
                          Net48Demo();
                      });
                    thread.Start();
                    thread.Join();
                    while(thread.ThreadState!=System.Threading.ThreadState.Stopped)
                    {}

                    if(thread.ThreadState==System.Threading.ThreadState.Stopped)
                    {
                        IsBusy = false;
                    }
                }
            }

            IsFirstFinished = true;
        }

        static void Net48Demo()
        {
            string net48Name = @"D:\C\ConsoleApp390\bin\Debug\ConsoleApp390.exe";
            Process proc=Process.Start(net48Name);
            proc.WaitForExit();
        }
        static void TestCore30Demo()
        {
            for (int i = 0; i < 10; i++)
            {
                if (!IsBusy)
                {
                    Console.WriteLine($"Test Core30Demo() {i}");
                    IsBusy = true;
                    Thread thread = new Thread(() =>
                    {
                        Core30Demo();
                    });
                    thread.Start();
                    thread.Join();
                    while (thread.ThreadState != System.Threading.ThreadState.Stopped)
                    { }

                    if (thread.ThreadState == System.Threading.ThreadState.Stopped)
                    {
                        IsBusy = false;
                    }
                }
            }
        }

        static void Core30Demo()
        {
            string core30Name = @"D:\C\ConsoleApp389\bin\Debug\netcoreapp3.0\ConsoleApp389.exe";
            Process proc=Process.Start(core30Name);
            proc.WaitForExit();
        }
    }
}

 

 

 I'll list serveral executed results.

In .net NewtonJson is faster than  System.Text.Json.JsonSerializer.Serialize.The  validated result as below.

1.

NewtonJsonDemo cost 1290 milliseconds.
JsonSerializerDemo cost 1404 milliseconds.

 2.

NewtonJsonDemo cost 1213 milliseconds.
JsonSerializerDemo cost 1814 milliseconds.

3.

NewtonJsonDemo cost 1305 milliseconds.
JsonSerializerDemo cost 1373 milliseconds.

4.

NewtonJsonDemo cost 1329 milliseconds.
JsonSerializerDemo cost 1749 milliseconds.

5.

NewtonJsonDemo cost 1234 milliseconds.
JsonSerializerDemo cost 1395 milliseconds.

While  in .net core 3.0 System.Text.Json.JsonSerializer.Serialize is faster than NewtonJson.

1.

NewtonJsonDemo cost 1704 milliseconds.
JsonSerializerDemo cost 1247 milliseconds.

2.

NewtonJsonDemo cost 1596 milliseconds.
JsonSerializerDemo cost 1451 milliseconds.

3.

NewtonJsonDemo cost 1430 milliseconds.
JsonSerializerDemo cost 1221 milliseconds.

4.

NewtonJsonDemo cost 1390 milliseconds.
JsonSerializerDemo cost 1219 milliseconds.

5.

NewtonJsonDemo cost 1334 milliseconds.
JsonSerializerDemo cost 1216 milliseconds.

 

Totally speaking, the .net core is completely faster than .net both in NewtonJson and System.Text.Json.JsonSerializer.Serialize

The data source come from Adventureworks2017.Sales.SalesOrderDetail table which has 121317 rows .

 

 

In  .net 4.8,now 201911221845464103 NewtonJsonDemo cost 1147 milliseconds.JsonSerializerDemo cost 1352 milliseconds.

In  .net 4.8,now 201911221845548941 NewtonJsonDemo cost 1082 milliseconds.JsonSerializerDemo cost 1263 milliseconds.

In  .net 4.8,now 201911221846033311 NewtonJsonDemo cost 1143 milliseconds.JsonSerializerDemo cost 1245 milliseconds.

In  .net 4.8,now 201911221846149554 NewtonJsonDemo cost 1109 milliseconds.JsonSerializerDemo cost 1210 milliseconds.

In  .net 4.8,now 201911221846233923 NewtonJsonDemo cost 1110 milliseconds.JsonSerializerDemo cost 1299 milliseconds.

In  .net 4.8,now 201911221846318762 NewtonJsonDemo cost 1140 milliseconds.JsonSerializerDemo cost 1253 milliseconds.

In  .net 4.8,now 201911221846403287 NewtonJsonDemo cost 1125 milliseconds.JsonSerializerDemo cost 1192 milliseconds.

In  .net 4.8,now 201911221846487188 NewtonJsonDemo cost 1215 milliseconds.JsonSerializerDemo cost 1219 milliseconds.

In  .net 4.8,now 201911221846569683 NewtonJsonDemo cost 1126 milliseconds.JsonSerializerDemo cost 1306 milliseconds.

In  .net 4.8,now 201911221847057021 NewtonJsonDemo cost 1121 milliseconds.JsonSerializerDemo cost 1322 milliseconds.

In .core 3.0,now 201911221847194044 NewtonJsonDemo cost 1172 milliseconds.JsonSerializerDemo cost 999 milliseconds.

In .core 3.0,now 201911221847269311 NewtonJsonDemo cost 1133 milliseconds.JsonSerializerDemo cost 1069 milliseconds.

In .core 3.0,now 201911221847343703 NewtonJsonDemo cost 1043 milliseconds.JsonSerializerDemo cost 941 milliseconds.

In .core 3.0,now 201911221847418622 NewtonJsonDemo cost 1098 milliseconds.JsonSerializerDemo cost 919 milliseconds.

In .core 3.0,now 201911221847492909 NewtonJsonDemo cost 1072 milliseconds.JsonSerializerDemo cost 1025 milliseconds.

In .core 3.0,now 201911221847567419 NewtonJsonDemo cost 1073 milliseconds.JsonSerializerDemo cost 1063 milliseconds.

In .core 3.0,now 201911221848041989 NewtonJsonDemo cost 1059 milliseconds.JsonSerializerDemo cost 1002 milliseconds.

In .core 3.0,now 201911221848125705 NewtonJsonDemo cost 1112 milliseconds.JsonSerializerDemo cost 880 milliseconds.

In .core 3.0,now 201911221848242935 NewtonJsonDemo cost 1116 milliseconds.JsonSerializerDemo cost 884 milliseconds.

In .core 3.0,now 201911221848318144 NewtonJsonDemo cost 1089 milliseconds.JsonSerializerDemo cost 991 milliseconds.

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • MiniProfiler 是一款性能分析的輕量級程式,可以基於action(request)記錄每個階段的耗時時長,還是可以顯示訪問資料庫時的SQL(支持EF、EF Code First)等 一、安裝程式包 通過Nuget安裝MiniProfiler : Install-Package MiniPr ...
  • 第一次寫隨筆,一名在實習的程式猿,做的一個小應用,需要的朋友可以參考參考, 使用WinForm實現了一個導入Excel,群發工資條的功能。功能已經實現,還不夠完善,。 大致運用了OleDbConnection,SMTP OleDbConnection來動態獲取Excel的數據 SMTP發郵件 簡單郵 ...
  • C#值類型和引用類型這個概念在剛學習的時候應該就知道了。但是我們並沒有深入的去理解它。越是基礎知識其實才是最有用的。對代碼的優化,代碼質量的提升都有幫助。通過整理本文章,對很多知識也起到了鞏固的作用吧。 1,值類型 值類型有:整型,浮點型,十進位,布爾型,struct,枚舉。值類型是線上程棧上分配的 ...
  • 1、公眾號配置坑--Token Token坑的自己弄個伺服器的地址和代碼,讓微信爸爸能訪問到。 例子: /// <summary>/// token驗證/// </summary>/// <param name="signature">signature結合了開發者填寫的token參數和請求中的ti ...
  • Swagger 是一款自動生成線上介面文檔+功能測試功能軟體 一、安裝程式包 通過管理 NuGet 程式包安裝,搜索Swashbuckle.AspNetCore 二、配置 Swagger 將 Swagger 添加到 Startup.ConfigureServices 方法中的服務集合中: 1 //註 ...
  • 一.未使用Swagger狀況 相信無論是前端開發人員還是後端開發人員,都或多或少都被介面文檔折磨過,前端經常抱怨後端給的介面文檔或與實際情況不一致。後端又覺得編寫及維護介面文檔會耗費不少精力,經常來不及更新。 其實無論是前端調用後端,還是後端調用後端,都期望有一個好的介面文檔。但是這個介面文檔對於程 ...
  • Code First模式 Code First是指"代碼優先"或"代碼先行"。 Code First模式將會基於編寫的類和配置,自動創建模型和資料庫。 一、準備工作 創建一個(.NetCore 類庫),命名為NetCoreWebApi.Model。 通過Nuget程式包安裝相關依賴 在類庫項目上右鍵 ...
  • 一、步驟 從“文件”菜單中選擇“新建”>“項目” 。 選擇“ASP.NET Core Web 應用程式”模板,再單擊“下一步” 。 將項目命名為 NetCoreWebApi,然後單擊“創建” 。 選擇“.NET Core”和“ASP.NET Core 2.2” 。 選擇“API”模板,然後單擊“創建 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...