Use singleton for zero-element arrays.

Create an easily-inlinable method that accesses the array used
by Enumerable.Empty (and hence not just shared within this project
but likely with the client assembly or other libraries it uses)
and use it anywhere a zero-element array is used, reducing allocations.
This commit is contained in:
Jon Hanna
2017-01-09 01:50:03 +00:00
parent 218c25c859
commit ff3bfaf51b
11 changed files with 69 additions and 39 deletions
@@ -87,40 +87,45 @@ namespace Newtonsoft.Json.Utilities
{
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression = new Expression[parametersInfo.Length];
IList<ByRefParameter> refParameterMap = new List<ByRefParameter>();
for (int i = 0; i < parametersInfo.Length; i++)
Expression[] argsExpression;
IList<ByRefParameter> refParameterMap;
if (parametersInfo.Length == 0)
{
ParameterInfo parameter = parametersInfo[i];
Type parameterType = parameter.ParameterType;
bool isByRef = false;
if (parameterType.IsByRef)
argsExpression = CollectionUtils.ArrayEmpty<Expression>();
refParameterMap = CollectionUtils.ArrayEmpty<ByRefParameter>();
}
else
{
argsExpression = new Expression[parametersInfo.Length];
refParameterMap = new List<ByRefParameter>();
for (int i = 0; i < parametersInfo.Length; i++)
{
parameterType = parameterType.GetElementType();
isByRef = true;
}
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
Expression argExpression = EnsureCastExpression(paramAccessorExpression, parameterType, !isByRef);
if (isByRef)
{
ParameterExpression variable = Expression.Variable(parameterType);
refParameterMap.Add(new ByRefParameter
ParameterInfo parameter = parametersInfo[i];
Type parameterType = parameter.ParameterType;
bool isByRef = false;
if (parameterType.IsByRef)
{
Value = argExpression,
Variable = variable,
IsOut = parameter.IsOut
});
parameterType = parameterType.GetElementType();
isByRef = true;
}
argExpression = variable;
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
Expression argExpression = EnsureCastExpression(paramAccessorExpression, parameterType, !isByRef);
if (isByRef)
{
ParameterExpression variable = Expression.Variable(parameterType);
refParameterMap.Add(new ByRefParameter {Value = argExpression, Variable = variable, IsOut = parameter.IsOut});
argExpression = variable;
}
argsExpression[i] = argExpression;
}
argsExpression[i] = argExpression;
}
Expression callExpression;