Consider this code:
var str1 = "1234567890qwertyuiop[asdfghjkl;zxcvbnm1,.";
Dictionary<string, Object> objects = new Dictionary<string, object> {{str1, new object()}};
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 100000000; i++)
{
object result;
objects.TryGetValue(str1, out result);
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
stopwatch.Reset();
//////////////////////////////////////////////////////////////
var list = new List<string>();
list.Add(str1);
stopwatch.Start();
for (int i = 0; i < 100000000; i++)
{
foreach (var item in list)
{
var result = "";
if (item == str1)
{
result = item;
}
}
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
When you run this code will see this result:
5157 // Dictionary
3881 // List
So the list is faster than a dictionary.
I want to know why. Is there any relation between string and length?