perf: Reduced size of JSON serialized nullable types

This commit is contained in:
Chris Cameron
2019-02-06 11:31:14 -05:00
parent d6abf3fdf6
commit 141d911eb0
2 changed files with 33 additions and 3 deletions

View File

@@ -155,6 +155,13 @@ namespace ICD.Common.Utils.Tests.Extensions
Assert.AreEqual(expected, type.GetNameWithoutGenericArity());
}
[TestCase(typeof(int), "System.Int32, System.Private.CoreLib")]
[TestCase(typeof(int?), "System.Nullable`1[[System.Int32, System.Private.CoreLib]], System.Private.CoreLib")]
public void GetNameWithoutAssemblyDetailsTest(Type type, string expected)
{
Assert.AreEqual(expected, type.GetNameWithoutAssemblyDetails());
}
[TestCase(typeof(string), "string")]
[TestCase(typeof(int?), "int?")]
[TestCase(typeof(List<int?>), "List<int?>")]

View File

@@ -7,6 +7,16 @@ namespace ICD.Common.Utils.Extensions
{
public static class JsonWriterExtensions
{
private static readonly Dictionary<Type, string> s_TypeToString;
/// <summary>
/// Static constructor.
/// </summary>
static JsonWriterExtensions()
{
s_TypeToString = new Dictionary<Type, string>();
}
/// <summary>
/// Writes the type value.
/// </summary>
@@ -24,9 +34,22 @@ namespace ICD.Common.Utils.Extensions
return;
}
string name = Type.GetType(type.FullName) == null
? type.GetNameWithoutAssemblyDetails()
: type.FullName;
string name;
if (!s_TypeToString.TryGetValue(type, out name))
{
// We'll use the full name if it can be deserialized.
// Full name ends up longer than name without assembly details when
// using nullables, so we do a length check to get the smallest possible
// string representation for the type.
string fullName = Type.GetType(type.FullName) == null ? null : type.FullName;
string nameWithoutAssembly = type.GetNameWithoutAssemblyDetails();
name = fullName == null || fullName.Length > nameWithoutAssembly.Length
? nameWithoutAssembly
: fullName;
s_TypeToString.Add(type, name);
}
extends.WriteValue(name);
}