Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement