检索字典价值的最佳实践字典、价值

2023-09-03 09:07:43 作者:此男洧點⒉

我刚刚注意到 Dictionary.TryGetValue(TKEY的钥匙,走出TValue值),是好奇,这是更好的方法来检索从字典的值。

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 Dictionary.

我已经做了传统的:

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

除非我知道它的的的是在那里。

是更好地只是做:

if (myDict.TryGetValue(somekey, out someVal)
    ...

哪个是更好的做法?是其中一个比另一个快?我可以想象在Try版本会更慢作为其吞咽一个try / catch内部本身,并将它作为逻辑的,不是吗?

Which is the better practice? Is one faster than the other? I would imagine that the Try version would be slower as its 'swallowing' a try/catch inside itself and using that as logic, no?

谢谢!

推荐答案

TryGetValue稍微快一些,因为FindEntry只会被调用一次。

TryGetValue is slightly faster, because FindEntry will only be called once.

快多少?这取决于   数据集在手。当调用   包含方法,字典里的   内部搜索找到它的索引。如果   它返回true,则需要另   索引搜索,获得的实际价值。   当您使用TryGetValue,它搜索   只有一次的索引,如果找到,   它的价值分配给您的变量。

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.

供参考:这不是真正捕捉错误。

FYI: It's not actually catching an error.

它调用的:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

的containsKey是这样的:

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}