perf: Significantly reducing the size of JSON serialized types

This commit is contained in:
Chris Cameron
2019-02-04 11:38:39 -05:00
parent 0700a357dd
commit 2dc705d335

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
using ICD.Common.Properties;
using Newtonsoft.Json;
@@ -7,6 +8,16 @@ namespace ICD.Common.Utils.Extensions
{
public static class JsonWriterExtensions
{
private static readonly Dictionary<Type, string> s_TypeToName;
/// <summary>
/// Static constructor.
/// </summary>
static JsonWriterExtensions()
{
s_TypeToName = new Dictionary<Type, string>();
}
/// <summary>
/// Writes the type value.
/// </summary>
@@ -24,11 +35,7 @@ namespace ICD.Common.Utils.Extensions
return;
}
// Find the smallest possible name representation for the type that will still resolve
string name = Type.GetType(type.FullName) == null
? type.AssemblyQualifiedName
: type.FullName;
string name = GetTypeName(type);
extends.WriteValue(name);
}
@@ -83,5 +90,76 @@ namespace ICD.Common.Utils.Extensions
}
writer.WriteEndArray();
}
/// <summary>
/// Gets the string representation foe the given type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static string GetTypeName(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
string name;
if (!s_TypeToName.TryGetValue(type, out name))
{
name = RemoveAssemblyDetails(type.AssemblyQualifiedName);
s_TypeToName.Add(type, name);
}
return name;
}
/// <summary>
/// Taken from Newtonsoft.Json.Utilities.ReflectionUtils
/// Removes the assembly details from a type assembly qualified name.
/// </summary>
/// <param name="fullyQualifiedTypeName"></param>
/// <returns></returns>
private static string RemoveAssemblyDetails(string fullyQualifiedTypeName)
{
StringBuilder builder = new StringBuilder();
// loop through the type name and filter out qualified assembly details from nested type names
bool writingAssemblyName = false;
bool skippingAssemblyDetails = false;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ']':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ',':
if (!writingAssemblyName)
{
writingAssemblyName = true;
builder.Append(current);
}
else
{
skippingAssemblyDetails = true;
}
break;
default:
if (!skippingAssemblyDetails)
{
builder.Append(current);
}
break;
}
}
return builder.ToString();
}
}
}