什么花费更少 CPU 时间/什么是 faster/smaller 负载? AddOrUpdate 或 if/else 与 TryAdd?

What takes less CPU time/ what is faster/smaller load? AddOrUpdate or if/else with TryAdd?

我有 KeyValuePairs,我想将新值添加到 ConcurrentDictonary。如果不包含密钥,我想添加它。 但是什么是 faster/better:

这个:

dict.AddOrUpdate(pair.Key, pair.Value, (ok, ov) => pair.Value);

或者这个:

if (dict.ContainsKey(pair.Key))
{
    dict[pair.Key] = pair.Value;
}
else
{
    dict.TryAdd(pair.Key, pair.Value);
}

我担心 AddOrUpdate 会做一些我没有做的额外工作want/need,而且它需要更长的时间,因为 Lambda 也必须执行。

这两种方法哪种更快?或者有更快的方法吗?

并发字典中的 AddOrUpdate 是原子操作,如果将其分离为两个方法调用 ContainsKeyTryAdd 它不再是原子操作,因此会破坏并发字典的目的。在这种情况下,您不必担心性能。

I am concerned that the AddOrUpdate does additional work that i don't want/need

这两个代码不等价。如果你想要线程安全使用 AddOrUpdate。如果线程安全不是问题,那么只需使用 Dictionary,它比 ConcurrentDictionary

更简单、更快

and that it takes longer because the Lambda has to be executed too.

执行 lambda 与执行其他方法一样快(如果您不属于微优化当然)