Skip to content

Instantly share code, notes, and snippets.

@mattak
Created May 26, 2016 03:20
Show Gist options
  • Select an option

  • Save mattak/a906581192937ed32bb71bc1e81f30ce to your computer and use it in GitHub Desktop.

Select an option

Save mattak/a906581192937ed32bb71bc1e81f30ce to your computer and use it in GitHub Desktop.
Json deserialization performance test in Unity3D.
using System;
using System.IO;
using Newtonsoft.Json;
using UnityEngine;
using UnityEditor;
using NUnit.Framework;
public class JsonPerformanceTest
{
[Serializable]
class SampleEntity
{
public int id;
public string name;
}
[Test]
public void EditorTest()
{
int n = 10000;
string json = "{\"name\":\"jojo\",\"id\":1}";
{
Assert.AreEqual(PerformUnityJsonConvert(json).name, "jojo");
Assert.AreEqual(PerformUnityJsonConvert(json).id, 1);
StartWatch();
for (int i = 0; i < n; i++) { PerformUnityJsonConvert(json); }
Debug.Log("UnityJson: " + StopWatch());
}
{
Assert.AreEqual(PerformJsonConvert(json).name, "jojo");
Assert.AreEqual(PerformJsonConvert(json).id, 1);
StartWatch();
for (int i = 0; i < n; i++) { PerformJsonConvert(json); }
Debug.Log("JsonConvert: " + StopWatch());
}
{
Assert.AreEqual(PerformJsonRawConvert(json).name, "jojo");
Assert.AreEqual(PerformJsonRawConvert(json).id, 1);
StartWatch();
for (int i = 0; i < n; i++) { PerformJsonRawConvert(json); }
Debug.Log("JsonConvertRaw: " + StopWatch());
}
}
private static long currentTime = 0;
private static void StartWatch() {
currentTime = CurrentTimeMillis();
}
private static long StopWatch() {
long diff = CurrentTimeMillis() - currentTime;
return diff;
}
private static long CurrentTimeMillis()
{
System.DateTime epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
return (long)(System.DateTime.UtcNow - epochStart).TotalMilliseconds;
}
private SampleEntity PerformUnityJsonConvert(string text) {
return JsonUtility.FromJson<SampleEntity>(text);
}
private SampleEntity PerformJsonConvert(string text)
{
return JsonConvert.DeserializeObject<SampleEntity>(text);
}
private SampleEntity PerformJsonRawConvert(string json)
{
SampleEntity entity = new SampleEntity();
string property = "";
using (var reader = new JsonTextReader(new StringReader(json)))
{
while (reader.Read())
{
if (reader.Value != null)
{
if (reader.TokenType == JsonToken.PropertyName)
{
property = reader.Value as string;
}
else if (reader.TokenType == JsonToken.String)
{
if (property.Equals("name"))
{
entity.name = reader.Value as string;
}
}
else if (reader.TokenType == JsonToken.Integer)
{
if (property.Equals("id"))
{
entity.id = int.Parse(reader.Value.ToString());
}
}
}
}
}
return entity;
}
}
@mattak
Copy link
Copy Markdown
Author

mattak commented May 26, 2016

result

take2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment