Port List changes from dotnet/coreclrdotnet/corefx#6212 (dotnet/corefx#9987)
authorJames Ko <jamesqko@gmail.com>
Tue, 12 Jul 2016 14:17:49 +0000 (10:17 -0400)
committerJan Kotas <jkotas@microsoft.com>
Tue, 12 Jul 2016 14:17:49 +0000 (16:17 +0200)
Commit migrated from https://github.com/dotnet/corefx/commit/2df67e0dafb452fce395aaf67dbcb59e63f08c7e

src/libraries/System.Collections/src/System/Collections/Generic/List.cs

index 9e1d426..5ac6d20 100644 (file)
@@ -338,26 +338,19 @@ namespace System.Collections.Generic
 
         // Contains returns true if the specified element is in the List.
         // It does a linear, O(n) search.  Equality is determined by calling
-        // item.Equals().
-        //
+        // EqualityComparer<T>.Default.Equals().
+
         public bool Contains(T item)
         {
-            if ((Object)item == null)
-            {
-                for (int i = 0; i < _size; i++)
-                    if ((Object)_items[i] == null)
-                        return true;
-                return false;
-            }
-            else
-            {
-                EqualityComparer<T> c = EqualityComparer<T>.Default;
-                for (int i = 0; i < _size; i++)
-                {
-                    if (c.Equals(_items[i], item)) return true;
-                }
-                return false;
-            }
+            // PERF: IndexOf calls Array.IndexOf, which internally
+            // calls EqualityComparer<T>.Default.IndexOf, which
+            // is specialized for different types. This
+            // boosts performance since instead of making a
+            // virtual method call each iteration of the loop,
+            // via EqualityComparer<T>.Default.Equals, we
+            // only make one virtual call to EqualityComparer.IndexOf.
+
+            return _size != 0 && IndexOf(item) != -1;
         }
 
         bool System.Collections.IList.Contains(Object item)