Skip to content

Use closure vs parameter in GetOrAdd type methods #63104

Answered by gfoidl
TahirAhmadov asked this question in Q&A
Discussion options

You must be logged in to vote

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.

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 onl…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@TahirAhmadov
Comment options

@gfoidl
Comment options

@TahirAhmadov
Comment options

@gfoidl
Comment options

Answer selected by TahirAhmadov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants