dictionary造成cpu过高

而当数据损坏的时候,灾难是不可预测的。举个例子,比如Dictionary内部用了很多的类似代码:

 1         private void Insert(TKey key, TValue value, bool add)
 2         {
 3             int freeList;
 4             if (key == null)
 5             {
 6                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
 7             }
 8             if (this.buckets == null)
 9             {
10                 this.Initialize(0);
11             }
12             int num = this.comparer.GetHashCode(key) & 0x7fffffff;
13             int index = num % this.buckets.Length;
14             int num3 = 0;
15             for (int i = this.buckets[index]; i >= 0; i = this.entries[i].next)
16             {
17                 if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
18                 {
19                     if (add)
20                     {
21                         ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
22                     }
23                     this.entries[i].value = value;
24                     this.version++;
25                     return;
26                 }
27                 num3++;
28             }
29             if (this.freeCount > 0)
30             {
31                 freeList = this.freeList;
32                 this.freeList = this.entries[freeList].next;
33                 this.freeCount--;
34             }
35             else
36             {
37                 if (this.count == this.entries.Length)
38                 {
39                     this.Resize();
40                     index = num % this.buckets.Length;
41                 }
42                 freeList = this.count;
43                 this.count++;
44             }
45             this.entries[freeList].hashCode = num;
46             this.entries[freeList].next = this.buckets[index];
47             this.entries[freeList].key = key;
48             this.entries[freeList].value = value;
49             this.buckets[index] = freeList;
50             this.version++;
51             if ((num3 > 100) && HashHelpers.IsWellKnownEqualityComparer(this.comparer))
52             {
53                 this.comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(this.comparer);
54                 this.Resize(this.entries.Length, true);
55             }
56         }

 for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
          ...
}
如果entries[i].next不幸地指向它自己,那么该for循环就是一个死循环,导致CPU高就不奇怪了。

原文地址:https://www.cnblogs.com/randymar/p/4272767.html