Enable HttpHeaderValueCollection.GetEnumerator to return an empty singleton (#47010)
authorStephen Toub <stoub@microsoft.com>
Fri, 15 Jan 2021 03:35:19 +0000 (22:35 -0500)
committerGitHub <noreply@github.com>
Fri, 15 Jan 2021 03:35:19 +0000 (22:35 -0500)
* Enable HttpHeaderValueCollection.GetEnumerator to return an empty singleton

An empty collection is common.  We can avoid the enumerator allocation in such cases.

* Update src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs

src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs

index 17c7759..68ba04e 100644 (file)
@@ -165,26 +165,25 @@ namespace System.Net.Http.Headers
         public IEnumerator<T> GetEnumerator()
         {
             object? storeValue = _store.GetParsedValues(_descriptor);
+            return storeValue is null ?
+                ((IEnumerable<T>)Array.Empty<T>()).GetEnumerator() : // use singleton empty array enumerator
+                Iterate(storeValue);
 
-            if (storeValue == null)
-            {
-                yield break;
-            }
-
-            List<object>? storeValues = storeValue as List<object>;
-
-            if (storeValues == null)
+            static IEnumerator<T> Iterate(object storeValue)
             {
-                Debug.Assert(storeValue is T);
-                yield return (T)storeValue;
-            }
-            else
-            {
-                // We have multiple values. Iterate through the values and return them.
-                foreach (object item in storeValues)
+                if (storeValue is List<object> storeValues)
+                {
+                    // We have multiple values. Iterate through the values and return them.
+                    foreach (object item in storeValues)
+                    {
+                        Debug.Assert(item is T);
+                        yield return (T)item;
+                    }
+                }
+                else
                 {
-                    Debug.Assert(item is T);
-                    yield return (T)item;
+                    Debug.Assert(storeValue is T);
+                    yield return (T)storeValue;
                 }
             }
         }