Optimize the += operation for a collection when it's an object array (#23901)

This commit is contained in:
Jordan Borean
2024-06-17 16:23:04 -07:00
committed by GitHub
parent 47e804a8c2
commit 6c66879c92
3 changed files with 20 additions and 0 deletions
@@ -39,6 +39,9 @@ namespace System.Management.Automation.Language
internal static readonly MethodInfo ObjectList_ToArray =
typeof(List<object>).GetMethod(nameof(List<object>.ToArray), Type.EmptyTypes);
internal static readonly MethodInfo ArrayOps_AddObject =
typeof(ArrayOps).GetMethod(nameof(ArrayOps.AddObjectArray), StaticFlags);
internal static readonly MethodInfo ArrayOps_GetMDArrayValue =
typeof(ArrayOps).GetMethod(nameof(ArrayOps.GetMDArrayValue), StaticFlags);
@@ -2717,6 +2717,14 @@ namespace System.Management.Automation.Language
lhsEnumerator.Expression.Cast(typeof(IEnumerator)),
rhsEnumerator.Expression.Cast(typeof(IEnumerator)));
}
else if (target.Value is object[] targetArray)
{
// Adding 1 item to an object[]
// This is an optimisation over the default EnumerableOps_AddObject.
call = Expression.Call(CachedReflectionInfo.ArrayOps_AddObject,
target.Expression.Cast(typeof(object[])),
arg.Expression.Cast(typeof(object)));
}
else
{
// Adding 1 item to a list
@@ -12,6 +12,15 @@ namespace System.Management.Automation
{
internal static class ArrayOps
{
internal static object AddObjectArray(object[] lhs, object rhs)
{
int newIdx = lhs.Length;
Array.Resize(ref lhs, newIdx + 1);
lhs[newIdx] = rhs;
return lhs;
}
internal static object[] SlicingIndex(object target, object[] indexes, Func<object, object, object> indexer)
{
var result = new object[indexes.Length];