From 68d98021a5e1262343c99c61b2ca8570f5986661 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Mon, 23 Sep 2019 11:43:54 -0400 Subject: [PATCH] perf: Micro-optimization for copying arrays --- .../Extensions/EnumerableExtensions.cs | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/ICD.Common.Utils/Extensions/EnumerableExtensions.cs b/ICD.Common.Utils/Extensions/EnumerableExtensions.cs index 8fcc131..ae1de2e 100644 --- a/ICD.Common.Utils/Extensions/EnumerableExtensions.cs +++ b/ICD.Common.Utils/Extensions/EnumerableExtensions.cs @@ -810,11 +810,29 @@ namespace ICD.Common.Utils.Extensions if (count < 0) throw new ArgumentOutOfRangeException("count"); - T[] array = new T[count]; - int i = 0; + // Source is already an array + T[] arrayCast = extends as T[]; + if (arrayCast != null) + { + T[] output = new T[count]; + Array.Copy(arrayCast, output, count); + return output; + } + // Dumb sequence case + T[] array = new T[count]; + + int i = 0; foreach (T item in extends) + { array[i++] = item; + if (i >= count) + break; + } + + if (i != count) + throw new ArgumentOutOfRangeException("count"); + return array; }