前后端分离的项目中,Json数据的处理,是经常遇到的。之前在项目中经常使用Newtonsoft这个类库,今天看到有人分享Jil这个Json库,性能会好一些。于是直接动手做了下测试,确实如此。直接上代码:
1.先引入需要的程序包:Jil和Newtonsoft
2.创建测试Model:Person
using System;
using System.Collections.Generic;
using System.Text;
namespace JsonConvertComparationProject
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}
3.主测试程序:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Jil;
using Newtonsoft.Json;
namespace JsonConvertComparationProject
{
class Program
{
static void Main(string[] args)
{
//测试两款Json序列化库的性能如何? Jil和Newtonsoft
//1.准备测试数据
var list = new List<Person>();
for (int i = 0; i < 1000000; i++)
{
list.Add(new Person() { Id = i });
}
var stop = new Stopwatch();
stop.Start();
string str1= JSON.Serialize(list);
Console.WriteLine(stop.ElapsedMilliseconds);
stop.Stop();
var stop1 = new Stopwatch();
stop1.Start();
string str2 = JsonConvert.SerializeObject(list);
Console.WriteLine(stop1.ElapsedMilliseconds);
stop1.Stop();
}
}
}
4.测试Result: