Use closure vs parameter in GetOrAdd type methods #63104
Answered
by
gfoidl
TahirAhmadov
asked this question in
Q&A
-
In many places in BCL and elsewhere, there are methods such as this: var dict = new ConcurrentDictionary<int, int>();
int input = 6;
int res = dict.GetOrAdd(input, input2 => input2 * 2); Note the parameter of the delegate (lambda) named |
Beta Was this translation helpful? Give feedback.
Answered by
gfoidl
Dec 23, 2021
Replies: 1 comment 4 replies
-
The main purpose is to provide a "value factory", that can construct the value to be added to the dictionary, based on the given key. E.g. private ConcurrentDictionary<int, MyHeavyType> _dict = new();
public MyHeavyType Naive(int key, Func<int, MyHeavyType> valueFactory)
{
// If the key is already present in the dictionary, the construction of MyHeavyType is done unnecessarily.
MyHeavyType value = valueFactory(key);
return _dict.GetOrAdd(key, value);
}
public MyHeavyType Better(int key, Func<int, MyHeavyType> valueFactory)
{
// The construction of MyHeavyType is only done when needed to do.
return _dict.GetOrAdd(key, valueFactory);
} |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
TahirAhmadov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The main purpose is to provide a "value factory", that can construct the value to be added to the dictionary, based on the given key.
This is very handy when the object to be constructed is costly, so it doesn't need to be done beforehands.
E.g.