Optimize Enumerable::ToArray
authorMarek Safar <marek.safar@gmail.com>
Tue, 8 Feb 2011 13:55:53 +0000 (13:55 +0000)
committerMarek Safar <marek.safar@gmail.com>
Tue, 8 Feb 2011 13:56:22 +0000 (13:56 +0000)
mcs/class/System.Core/System.Linq/Enumerable.cs

index 74a6123e33af4a372063c1f13752ff485de4bf8b..0f9b717b4af71fb1ebd043426132fb0490269ea9 100644 (file)
@@ -2791,14 +2791,34 @@ namespace System.Linq
                {
                        Check.Source (source);
 
+                       TSource[] array;
                        var collection = source as ICollection<TSource>;
                        if (collection != null) {
-                               var array = new TSource [collection.Count];
+                               if (collection.Count == 0)
+                                       return EmptyOf<TSource>.Instance;
+                               
+                               array = new TSource [collection.Count];
                                collection.CopyTo (array, 0);
                                return array;
                        }
+                       
+                       int pos = 0;
+                       array = EmptyOf<TSource>.Instance;
+                       foreach (var element in source) {
+                               if (pos == array.Length) {
+                                       if (pos == 0)
+                                               array = new TSource [4];
+                                       else
+                                               Array.Resize (ref array, pos * 2);
+                               }
 
-                       return new List<TSource> (source).ToArray ();
+                               array[pos++] = element;
+                       }
+
+                       if (pos != array.Length)
+                               Array.Resize (ref array, pos);
+                       
+                       return array;
                }
 
                #endregion