C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: Contains is an extension method, and can be called on arrays, Lists and certain other collections.
ExtensionNote 2: Some collections, such as List, contain their own Contains method—this is an instance method. Performance is better.
Info: In this example, the first Contains call specifies the type parameter int in the angle brackets.
And: This tells the C# compiler to select the extension method version of Contains, not the List type's version.
Generic Class, MethodC# program that uses Contains
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Use extension method.
bool a = list.Contains<int>(7);
// Use instance method.
bool b = list.Contains(7);
Console.WriteLine(a);
Console.WriteLine(b);
}
}
Output
True
True
Note: In this benchmark, the Contains methods both return true as in the above program.
BenchmarkNote 2: The exception code is used to ensure the C# compiler does not optimize out the Contains calls.
Result: The Contains method (on List) is faster than the Contains extension. It thus should be preferred.
List used in benchmark: C#
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Inner loop tested 1: C#
bool a = list.Contains<int>(7);
if (!a)
{
throw new Exception();
}
Inner loop tested 2: C#
bool b = list.Contains(7);
if (!b)
{
throw new Exception();
}
Output
46.50 ns Extension method
39.99 ns List method
So: The performance disparity here is mainly due to more low-level code in List Contains.
And: List Contains internally does not use enumerators or MoveNext—it uses a loop construct and checks elements. This is lower-level.
List Contains