Retrieving Dictionary Value Best Practices

前端 未结 3 863
遥遥无期
遥遥无期 2020-12-24 04:22

I just recently noticed Dictionary.TryGetValue(TKey key, out TValue value) and was curious as to which is the better approach to retrieving a value from the Dic

3条回答
  •  被撕碎了的回忆
    2020-12-24 04:57

    Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

    Edit:

    Ok, I understand your confusion so let me elaborate:

    Case 1:

    if (myDict.Contains(someKey))
         someVal = myDict[someKey];
    

    In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it

    Case 2:

    myDict.TryGetValue(somekey, out someVal)
    

    In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.

提交回复
热议问题