如果您想通过某个标识符在包含 32k 元素的集合中快速搜索,您应该使用 Dictionary<K,V> 作为您的集合。
var dict = new Dictionary<IDType, MessageType>();
字典基本上是一个搜索树,其中元素以排序方式存储,因此无需查看所有元素即可找到具有特定键(在您的情况下为 ID)的元素。有关详细信息,请参阅MSDN。
如果您不能将集合重构为字典,您可以先填充字典(慢),然后在字典中搜索(快)。如果您在再次填写字典之前进行多次搜索,即如果您的列表不经常更改,这只会更快。
foreach(object o in List)
{
var msg = (MessageType)o;
dict.Add(msg.Id, msg);
}
然后搜索很容易:
MessageType msg = dict[id];
编辑:嗯,我很好奇,写了一个测试例程来比较线性搜索和字典方法。这是我使用的:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace ConsoleApplication1
{
class MessageType
{
public string Id;
public string Text;
}
class Program
{
static void Main(string[] args)
{
var rand = new Random ();
// filling a list with random text messages
List<MessageType> list = new List<MessageType>();
for (int i = 0; i < 32000; i++)
{
string txt = rand.NextDouble().ToString();
var msg = new MessageType() {Id = i.ToString(), Text = txt };
list.Add(msg);
}
IList List = (IList)list;
// doing some random searches
foreach (int some in new int[] { 2, 10, 100, 1000 })
{
var watch1 = new Stopwatch();
var watch2 = new Stopwatch();
Dictionary<string, MessageType> dict = null;
for (int i = 0; i < some; i++)
{
string id = rand.Next(32000).ToString();
watch1.Start();
LinearLookup(List, id);
watch1.Stop();
watch2.Start();
// fill once
if (dict == null)
{
dict = new Dictionary<string, MessageType>();
foreach (object o in List)
{
var msg = (MessageType)o;
dict.Add(msg.Id, msg);
}
}
// lookup
DictionaryLookup(dict, id);
watch2.Stop();
}
Console.WriteLine(some + " x LinearLookup took "
+ watch1.Elapsed.TotalSeconds + "s");
Console.WriteLine("Dictionary fill and " + some
+ " x DictionaryLookup took "
+ watch2.Elapsed.TotalSeconds + "s");
}
}
static string LinearLookup(IList List, string id)
{
foreach (object myObj in List)
{
if (((MessageType)myObj).Id == id)
{
return ((MessageType)myObj).Text;
}
}
throw new Exception();
}
static string DictionaryLookup(Dictionary<string, MessageType> dict,
string id)
{
return dict[id].Text;
}
}
}
我在 Release / x86 中得到的结果:
Number of | Time [ms] with | Time[ms] with | Speedup (approx.)
searches | linear search | dictionary(*) | with dictionary
----------+----------------+---------------+-----------------
2 | 1.161 | 2.006 | 0.6
----------+----------------+---------------+-----------------
10 | 2.834 | 2.060 | 1.4
----------+----------------+---------------+-----------------
100 | 25.39 | 1.973 | 13
----------+----------------+---------------+-----------------
1000 | 261.4 | 5.836 | 45
----------+----------------+---------------+-----------------
(*) including filling the dictionary once.
所以,我有点乐观地说,搜索两次就会有回报。在我的测试应用程序中,我必须搜索 10 次字典才能更快。
很抱歉,我无法举一个更现实的例子,我的 ID 都已排序。不过,请随意尝试修改和试验 ;-)