Skip to content

Latest commit

 

History

History
27 lines (24 loc) · 1.4 KB

2022-02-03 kvp в качестве ключа словаря.md

File metadata and controls

27 lines (24 loc) · 1.4 KB

На ревью вот такой код

var dict = new Dictionary<KeyValuePair<string, string>, string>();
for (int i = 0; i <= 10000; i++)
{
    var key = new KeyValuePair<string, string>("key", $"value_{i}");
    dict.Add(key, $"{i}");
}

пропускать не стоит. В нём есть технический изъян.

GetHashCode() будет возвращать одинаковое значение. В итоге вместо сложности O(1) получаем сложность O(N)

https://referencesource.microsoft.com/#mscorlib/system/valuetype.cs,75

/*=================================GetHashCode==================================
**Action: Our algorithm for returning the hashcode is a little bit complex.  We look
**        for the first non-static field and get it's hashcode. If the type has no
**        non-static fields, we return the hashcode of the type. We can't take the
**        hashcode of a static member because if that member is of the same type as
**        the original type, we'll end up in an infinite loop.
**Returns: The hashcode for the type.
  1. Если есть хоть один реф-тайп, то будет хэш-код по первому полю
  2. Если там нет реф-тайпов, то ксорят филды https://github.com/dotnet/runtime/blob/57bfe474518ab5b7cfe6bf7424a79ce3af9d6657/src/coreclr/vm/comutilnative.cpp#L1858