Unity-NewtonsoftJsonLitJson和SimpleJSON性能对比

33次阅读

共计 2211 个字符,预计需要花费 6 分钟才能阅读完成。

Unity 中 Json 库性能对比测试

类库大小对比:

类库 文件类型 大小
NewtonsoftJson .dll 353KB
LitJson .dll 56KB
SimpleJSON .cs 68KB

解析时间对比:
执行次数:10000 次

测试方法 NewtonsoftJson LitJson SimpleJSON
测试 1 114ms 158ms 52ms
测试 2 136ms 288ms 126ms
测试 3 263ms 542ms 169ms
测试 4 333ms 747ms 200ms

测试代码:

using UnityEngine;
using System.Diagnostics;
using LitJson;
using SimpleJSON;
using Newtonsoft.Json.Linq;

/// <summary>
/// JsonTest
/// ZhangYu 2019-07-11
/// <para> 文章地址: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/Si…

正文完
 0