本文介绍了有理由为什么应该在TryGetValue上使用ContainsKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了一些测试,无论是否命中都没关系.TryGetValue总是更快.什么时候应该使用ContainsKey?

I have tried some tests and it does not matter if there are all hits or miss. TryGetValue is always faster. When one should use ContainsKey?

推荐答案

这取决于您使用什么方法.如果打开参考源,您将看到./p>

It depends for what are you using the methods. If you open Reference source you will see.

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;
}

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

就像您看到的 TryGetValue ContainsKey +一个数组查找一样.

Like you see TryGetValue is same as ContainsKey + one array lookup.

如果您的逻辑只是检查密钥是否存在于 Dictionary 中,并且与此密钥无关(获取密钥值),则应使用 ContainsKey.

If your logic is only to check if the key is existing in the Dictionary and nothing else related to this key (taking the value for the key) you should use ContainsKey.

如果要获取特定键的值,则 TryGetValue 的速度比

If you want to take the value for the specific key, TryGetValue is faster than

if(dic.ContainsKey(keyValue))
{
    dicValue = dic[keyValue]; // here you do more work!
}

关于 Dictionary [key]

    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 一起使用,然后在 dic中取值,那么您将在 FindEntry 方法+数组查找中进行2次操作[键] .您有额外的时间呼叫 FindEntry 的开销.

So pretty much you will go 2 times in FindEntry method + array lookup, if you use the key with ContainsKey and after that take the value with dic[key]. You have overhead of calling FindEntry one additional time.

这篇关于有理由为什么应该在TryGetValue上使用ContainsKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 00:16