Unity JSON性能对比(LitJson、NewtonsoftJson、SimpleJSON)

tech2025-01-27  31

@[toc](Unity JSON性能对比(LitJson、NewtonsoftJson、SimpleJSON))

Unity中Json库性能对比测试

类库大小对比:

类库文件类型大小NewtonsoftJson.dll353KBLitJson.dll56KBSimpleJSON.cs68KB

解析时间对比:

执行次数:10000次

测试方法NewtonsoftJsonLitJsonSimpleJSON测试1114ms158ms52ms测试2136ms288ms126ms测试3263ms542ms169ms测试4333ms747ms200ms

测试代码

using UnityEngine; using System.Diagnostics; using LitJson; using SimpleJSON; using Newtonsoft.Json.Linq; /// <summary> /// JsonTest /// ZhangYu 2019-07-11 /// <para>Blog:https://segmentfault.com/a/1190000019731298</para> /// </summary> public class JsonTest : MonoBehaviour { public int count = 10000; private Stopwatch watch; private void Start () { watch = new Stopwatch(); string json1 = "{\"id\":10001,\"name\":\"test\"}"; string json2 = "[1,2,3,4,5,6,7,8,9,10]"; string json3 = "{\"id\":10000,\"username\":\"zhangyu\",\"password\":\"123456\",\"nickname\":\"冰封百度\",\"age\":20,\"gender\":1,\"phone\":12345678910,\"email\":\"zhangyu@xx.com\"}"; string json4 = "[\"test2\",[[\"key1\", \"id\"],[\"key2\", \"hp\"],[\"key3\", \"mp\"],[\"key4\", \"exp\"],[\"key5\", \"money\"],[\"key6\", \"point\"],[\"key7\", \"age\"],[\"key8\", \"sex\"]]]"; JsonParseTest(json1); JsonParseTest(json2); JsonParseTest(json3); JsonParseTest(json4); } private void JsonParseTest(string json) { print("json:" + json); bool isArray = json[0] == '['; NewtonsoftJsonTest(json, isArray); LiteJsonTest(json); SimpleJsonTest(json); print("======================"); } private void NewtonsoftJsonTest(string json, bool isArray) { watch.Reset(); watch.Start(); if (isArray) { for (int i = 0; i < count; i++) { JArray jArray = JArray.Parse(json); } } else { for (int i = 0; i < count; i++) { JObject jObj = JObject.Parse(json); } } watch.Stop(); print("NewtonsoftJson Parse Time(ms):" + watch.ElapsedMilliseconds); } private void LiteJsonTest(string json) { watch.Reset(); watch.Start(); for (int i = 0; i < count; i++) { JsonData jData = JsonMapper.ToObject(json); } watch.Stop(); print("LiteJson Parse Time(ms):" + watch.ElapsedMilliseconds); } private void SimpleJsonTest(string json) { watch.Reset(); watch.Start(); for (int i = 0; i < count; i++) { JSONNode jNode = JSON.Parse(json); } watch.Stop(); print("SimpleJson Parse Time(ms):" + watch.ElapsedMilliseconds); } }

结果

结论

SimpleJSON获胜! SimpleJSON以体积最小,速度最快,集成最容易的优势胜出。 SimpleJSON针对Unity在持续优化,更新较快,而且体积小,速度快,有源码,推荐SimpleJSON。 NewtonsoftJson因为体积太大被淘汰,按理来说,这么大的类库肯定支持更多功能,可惜现有的项目并没有太过复杂的json,无法检验。 LitJson体积也小巧,使用也很方便,可惜速度完全没有优势。

SimpleJSON的Github地址:https://github.com/Bunny83/SimpleJSON

最新回复(0)