最近我收到了评论评论,使用Dictionary而不是List,其中代码根据添加到List的对象属性进行了一些搜索。为了使用字典,我必须构建一个密钥,然后根据该密钥搜索对象。
我有一些想法,考虑到我们需要对其进行的收集大小和搜索次数,它不会对我们产生任何重大影响。所以只想在两者之间做一些性能比较。按照我写的代码进行比较。这段代码正在构建一个500到5000集合的字典和列表,然后使用不同的密钥大小(5% - 集合大小的20%)我测试了这段代码。
class Program
{
static void Main(string[] args)
{
string quit = "";
do
{
for (int size = 500; size <= 5000; size+=500)
{
int keySize = Convert.ToInt32(size/5);
RunTest(size, keySize);
}
quit = Console.ReadKey().ToString();
}
while (quit != "q");
}
private static void RunTest(int size, int keySize)
{
string[] keysToFind = GetKeysToFind(size, keySize);
var dictTime = DateTime.Now;
var dict = getDictionary(size);
for (int i = 0; i < keysToFind.Length; i++)
{
var str = dict[keysToFind[i]];
}
var totalDictTime = DateTime.Now.Subtract(dictTime).Milliseconds;
var listTime = DateTime.Now;
var list = getList(size);
for (int i = 0; i < keysToFind.Length; i++)
{
var str = list.FirstOrDefault(item => item == keysToFind[i]);
}
var totalListTime = DateTime.Now.Subtract(listTime).Milliseconds;
Console.WriteLine("Total time taken by Dictionary: {0}, Size: {1}, Keysize: {2}", totalDictTime, dict.Count, keysToFind.Length);
Console.WriteLine("Total time taken by List : {0}, Size: {1}, Keysize: {2}", totalListTime, list.Count, keysToFind.Length);
}
private static string[] GetKeysToFind(int maxSize, int keySize)
{
var random = new Random();
var ret = new string[keySize];
for (int i = 0; i < keySize; i++)
ret[i] = "K" + random.Next(0, maxSize);
return ret;
}
private static Dictionary<string, double> getDictionary(int size)
{
var dict = new Dictionary<string, double>();
for(double i =0;i<size;i++)
{
dict.Add("K" + i, i + 10000);
}
return dict;
}
private static List<string> getList(int size)
{
var list = new List<string>();
for (double i = 0; i < size; i++)
{
list.Add("K" + i);
}
return list;
}
}