From cc9e1c1a65ccba46e9fa35b65251fae84767b6d6 Mon Sep 17 00:00:00 2001 From: RogueException Date: Sat, 20 Aug 2016 20:57:25 -0300 Subject: [PATCH] Improve array conversion for paramslist --- src/Discord.Net.Commands/CommandParser.cs | 30 +++++++++++++++++------ 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/Discord.Net.Commands/CommandParser.cs b/src/Discord.Net.Commands/CommandParser.cs index ad43758e3..1a4368a31 100644 --- a/src/Discord.Net.Commands/CommandParser.cs +++ b/src/Discord.Net.Commands/CommandParser.cs @@ -1,8 +1,10 @@ -using System.Collections.Immutable; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Reflection; using System.Text; using System.Threading.Tasks; -using System.Collections.Generic; -using System; namespace Discord.Commands { @@ -14,6 +16,9 @@ namespace Discord.Commands Parameter, QuotedParameter } + + private static readonly MethodInfo _convertArrayMethod = typeof(CommandParser).GetTypeInfo().GetDeclaredMethod(nameof(ConvertParamsList)); + private static readonly ConcurrentDictionary, object>> _arrayConverters = new ConcurrentDictionary, object>>(); public static async Task ParseArgs(Command command, IMessage context, string input, int startPos) { @@ -122,11 +127,12 @@ namespace Discord.Commands if (curPos == endPos) { - Array realParams = Array.CreateInstance(curParam.ElementType, paramsList.Count); - for (int i = 0; i < paramsList.Count; i++) - realParams.SetValue(Convert.ChangeType(paramsList[i], curParam.ElementType), i); - - argList.Add(realParams); + var func = _arrayConverters.GetOrAdd(curParam.ElementType, t => + { + var method = _convertArrayMethod.MakeGenericMethod(t); + return (Func, object>)method.CreateDelegate(typeof(Func, object>)); + }); + argList.Add(func.Invoke(paramsList)); curParam = null; curPart = ParserPart.None; @@ -169,5 +175,13 @@ namespace Discord.Commands return ParseResult.FromSuccess(argList.ToImmutable()); } + + private static T[] ConvertParamsList(List paramsList) + { + var array = new T[paramsList.Count]; + for (int i = 0; i < array.Length; i++) + array[i] = (T)paramsList[i]; + return array; + } } }