We benchmark the performance of List Contains and a custom for-loop on a small List. Only a few elements are searched by each method.
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
/// <summary>
/// Custom implementation.
/// </summary>
static bool ContainsLoop(List<string> list, string value)
{
for (int i = 0; i < list.Count; i++)
{
if (list[i] == value)
{
return true;
}
}
return false;
}
const int _max = 100000000;
static void Main()
{
var list = new List<string>();
list.Add(
"one");
list.Add(
"two");
list.Add(
"three");
list.Add(
"four");
list.Add(
"five");
var s1 = Stopwatch.StartNew();
// Version 1: use loop to search a list.
for (int i = 0; i < _max; i++)
{
bool f = ContainsLoop(list,
"four");
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use Contains method.
for (int i = 0; i < _max; i++)
{
bool f = list.Contains(
"four");
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
19.22 ns For-loop, string comparisons [ContainsLoop]
54.60 ns Contains method [Contains]