Unity中Json库性能对比测试
类库大小对比:
NewtonsoftJson 353KB LitJson SimpleJSON
解析时间对比:
执行次数:10000次
测试代码:
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\":\"[email protected]\"}";
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);