Ali*_*tad 24
首先,Dictionary
[UPDATED]使用密钥的哈希码在其内部存储中找到它们 - 而不是密钥.而Hashcode是一个int
.对int
,它是正义的价值int
,对于string
它产生.
因此,使用int
是稍快.
事实上,为字符串生成哈希代码是一个相当复杂的过程(使用Reflector的代码段)[ 希望这不作为版权漏洞,因为它不是 ]:
fixed (char* str = ((char*) this))
{
char* chPtr = str;
int num = 0x15051505;
int num2 = num;
int* numPtr = (int*) chPtr;
for (int i = this.Length; i > 0; i -= 4)
{
num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0];
if (i <= 2)
{
break;
}
num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1];
numPtr += 2;
}
return (num + (num2 * 0x5d588b65));
}
Run Code Online (Sandbox Code Playgroud)
我知道这已经很老了并且回答了问题,所以这个答案适用于将来寻找它的每个人.对我来说这是一个有趣的问题,我试图找到这个问题的实际答案,结果非常有趣.
通常String作为键比作为键要慢得多.
码:
class Program
{
object obj = new object();
Dictionary<long, object> longDict = new Dictionary<long, object>();
Dictionary<string, object> stringDict = new Dictionary<string, object>();
public static void Main(string[] args)
{
Program hash = new Program();
hash.Test(1000);
hash.Test(10000);
hash.Test(100000);
hash.Test(1000000);
hash.Test(10000000);
Console.Read();
}
private void Test(int iterations)
{
Console.WriteLine(String.Format("Test for {0} iterations", iterations));
longDict.Clear();
stringDict.Clear();
for (int i = 0; i < iterations; i++)
{
longDict.Add(i, obj);
}
for (int i = 0; i < iterations; i++)
{
stringDict.Add(i.ToString(), obj);
}
IntTest(iterations);
StringTest(iterations);
}
private void IntTest(int iteraions)
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
object test;
for (int i = 0; i < iteraions; i++) {
test = longDict[i];
}
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
}
private void StringTest(int iteraions)
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
object test;
for (int i = 0; i < iteraions; i++)
{
test = stringDict[i.ToString()];
}
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
}
}
Run Code Online (Sandbox Code Playgroud)
结果: