Join GitHub today
Call TryGetValue in overload of ConcurrentDictionary.GetOrAdd to avoid acquiring lock #631
There are two overloads of ConcurrentDictionary.GetOrAdd. One accepts a factory
The other overload, however, does not call TryGetValue - it simply calls
I agree this change maps better to the stated behavior of ConcurrentDictionary.
I was still a little concerned about the performance impact this could have, as it would make the add case a bit more expensive (a failed lookup) in favor of making the get case less expensive (no lock required). I played around with it a bit, and it seems like worst case this negatively impacts the add case by around 8% or so, whereas this consistently improves the get case by anywhere from 30-100% improvement (and that's without contention, which would decrease the negative impact for add and increase the positive improvement for get), depending on various factors and assuming a relatively trivial GetHashCode, as for Int32 (a more expensive hash code function would just decrease the impact of the change). Since ConcurrentDictionary is typically used in scenarios with frequent gets and less frequent adds, this seems like the right tradeoff to make.