Skip to content

Commit d44ac2b

Browse files
committed
Add typed fast paths in ReadArray for common element types
Avoid Array.CreateInstance + Array.SetValue reflection overhead for object[], string[], and Type[] arrays in metadata deserialization.
1 parent 0e0c2e1 commit d44ac2b

1 file changed

Lines changed: 37 additions & 2 deletions

File tree

src/Microsoft.VisualStudio.Composition/Configuration/SerializationContextBase.cs

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,15 @@ internal abstract partial class SerializationContextBase : IDisposable
5757

5858
private static readonly object BoxedTrue = true;
5959
private static readonly object BoxedFalse = false;
60+
61+
private static readonly IReadOnlyDictionary<string, object?> EmptyMetadata = ImmutableDictionary<string, object?>.Empty;
6062
private static readonly object BoxedCreationPolicyAny = CreationPolicy.Any;
6163
private static readonly object BoxedCreationPolicyShared = CreationPolicy.Shared;
6264
private static readonly object BoxedCreationPolicyNonShared = CreationPolicy.NonShared;
6365
private static readonly object BoxedInt32Zero = 0;
6466
private static readonly object BoxedInt32One = 1;
6567
private static readonly object BoxedInt32NegativeOne = -1;
6668

67-
private static readonly IReadOnlyDictionary<string, object?> EmptyMetadata = ImmutableDictionary<string, object?>.Empty;
68-
6969
internal SerializationContextBase(BinaryReader reader, Resolver resolver)
7070
{
7171
Requires.NotNull(reader, nameof(reader));
@@ -758,6 +758,41 @@ protected Array ReadArray(BinaryReader reader, Func<object?> itemReader, Type el
758758
throw new NotSupportedException();
759759
}
760760

761+
// Use typed fast paths for common element types to avoid
762+
// the reflection overhead of Array.CreateInstance + Array.SetValue.
763+
if (elementType == typeof(object))
764+
{
765+
var array = new object?[(int)count];
766+
for (int i = 0; i < array.Length; i++)
767+
{
768+
array[i] = itemReader();
769+
}
770+
771+
return array;
772+
}
773+
774+
if (elementType == typeof(string))
775+
{
776+
var array = new string?[(int)count];
777+
for (int i = 0; i < array.Length; i++)
778+
{
779+
array[i] = (string?)itemReader();
780+
}
781+
782+
return array;
783+
}
784+
785+
if (elementType == typeof(Type))
786+
{
787+
var array = new Type?[(int)count];
788+
for (int i = 0; i < array.Length; i++)
789+
{
790+
array[i] = (Type?)itemReader();
791+
}
792+
793+
return array;
794+
}
795+
761796
var list = Array.CreateInstance(elementType, (int)count);
762797
for (int i = 0; i < list.Length; i++)
763798
{

0 commit comments

Comments
 (0)