List<string>(map.Keys) vs map.Keys.ToList()
The following codes compare the List<string>(map.Keys) and map.Keys.ToList(). The results seems to suggest that there is no conclusive comparison
Dictionary<string, string> map = new Dictionary<string, string>();
for (int i = 0; i < 1000000; ++i)
{
map[i.ToString()] = i.ToString();
}
for (int k = 0; k < 5; ++k)
{
double time1 = 0;
double time2 = 0;
for (int i = 0; i < 300; ++i)
{
DateTime start_time = DateTime.Now;
List<string> keys = new List<string>(map.Keys);
DateTime end_time = DateTime.Now;
TimeSpan ts = end_time - start_time;
time1 += ts.TotalMilliseconds;
start_time = DateTime.Now;
keys = map.Keys.ToList();
end_time = DateTime.Now;
ts = end_time - start_time;
time2 += ts.TotalMilliseconds;
}
//Console.WriteLine("TimeSpan1: {0} ms", time1);
//Console.WriteLine("TimeSpan2: {0} ms", time2);
if (time1 > time2)
{
Console.WriteLine("++ new List<string>(map.Keys) is better");
}
else if (time1 < time2)
{
Console.WriteLine("++ map.Keys.ToList() is better");
}
}
No comments:
Post a Comment