【C#】Dictionary的TryGetValue和Contains使用、性能比较

  • 使用 TryGetValue,用out返回值

if (Dictionary.TryGetValue(key, out value))
{

}
  • TryGetValue对应源码:

public bool TryGetValue(TKey key, out TValue value)
{
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }
    lock (_lock)
    {
        VerifyIntegrity();
        return TryGetValueWorker(key, out value);
    }
}

private bool TryGetValueWorker(TKey key, out TValue value)
{
    int entryIndex = FindEntry(key);
    if (entryIndex != -1)
    {
        Object primary = null;
        Object secondary = null;
        _entries[entryIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
        // Now that we've secured a strong reference to the secondary, must check the primary again
        // to ensure it didn't expire (otherwise, we open a ---- where TryGetValue misreports an
        // expired key as a live key with a null value.)
        if (primary != null)
        {
            value = (TValue)secondary;
            return true;
        }
    }

    value = default(TValue);
    return false;
}

可以看到,获取字典的一个值时,TryGetValue,使用了一次FindEntry,然后直接根据索引,取到了对应的值。

  • 使用 ContainsKey判断是否存在,用索引返回值

if(Dictionary.ContainsKey(key))
{
    var value = Dictionary[key];
}
  • ContainsKey源码实现:

public bool ContainsKey(TKey key)
{
    return FindEntry(key) >= 0;
}
public TValue this[TKey key]
{
    get
    {
        int i = FindEntry(key);
        if (i >= 0) return entries[i].value;
        ThrowHelper.ThrowKeyNotFoundException();
        return default(TValue);
    }
    set
    {
        Insert(key, value, false);
    }
}

可以看到,判断ContainsKey的时候调用一次FindEntry,使用索引取值的时候又是用了一次FindEntry。

结论

TryGetValue,调用1次FindEntry取到想要的值【推荐使用】。

ContainsKey,调用2次FindEntry取到想要的值。

猜你喜欢

转载自blog.csdn.net/Ling_SevoL_Y/article/details/129559838