A dictionary with a tuple key is slower than a nested dictionary. What for?

I tested the speed of extracting, updating, and deleting values ​​in a dictionary using the (int, int, string) tuple as a key compared to the same nested dictionary: Dictionary →.

My tests show that the dictionary of tuples is much slower (58% for extracting, 69% for updating and 200% for deleting). I did not expect this. A nested dictionary should do more searches, so why is the dictionary dictionary so much slower?

My test code is:

    public static object TupleDic_RemoveValue(object[] param)
    {
        var dic = param[0] as Dictionary<(int did, int eid, string name), string>;
        var keysToRetrieve = param[2] as List<(int did, int eid, string name)>;

        foreach (var key in keysToRetrieve)
        {
            dic.Remove(key);
        }

        return dic;

    }


    public static object NestedDic_RemoveValue(object[] param)
    {
        var dic = param[1] as Dictionary<int, Dictionary<int, Dictionary<string, string>>>;
        var keysToRetrieve = param[2] as List<(int did, int eid, string name)>;


        foreach (var key in keysToRetrieve)
        {
            if (dic.TryGetValue(key.did, out var elementMap) && elementMap.TryGetValue(key.eid, out var propertyMap))
                propertyMap.Remove(key.name);
        }

        return dic;

    }

: 10 000 . : ([0-100], [0-100], " [0-100]" ). 100 ( 10% ), 100 ( 10% ) 100 ( 10% ). , 3 . 1000 . .

+4
1

Dictionary . - - , . -, Equals ( -) , .

ValueTuple - ( arity-2 + *) Equality Comparer.Default<T>.GetHashCode . ValueTuple.CombineHashCodes, System.Numerics.Hashing.HashHelpers.Combine. , Combine. int GetHashCode, .

, . , . GetHashCode Equals. , , Equals ( EqualityComparer<T>.Default.Equals ).

, ( , - , , ..), .

(, ), , -/ , ValueTuple s. , .

* , 1- .

HashHelpers.Combine

ValueTuple

Int32.GetHashCode

+4

Source: https://habr.com/ru/post/1694125/


All Articles