Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dictionary TryGetValue with int values, how to avoid double lookup

When doing something like:

int value;
if (dict.TryGetValue(key, out value))
{
    if (condition)
    {
        //value = 0;  this copies by value so it doesn't change the existing value
        dict[key] = 0;
    }
}
else
{
    dict[key] = 0;
}

Is there any way I can avoid index lookup to replace the existing value? I'm already verifying the key exists using TryGetValue so it seems like a waste to have to retrieve value by index again.

On a separate note, as in the else{} part of my code, is it generally considered good practice to use the indexer when adding new or replacing old values, and add to make it clear you are adding and not replacing? Or should I just use the indexer every time? The way I have learned to use dictionary, I always do a TryGetValue lookup and in the else portion I handle cases where no key exists.

like image 337
tmakino Avatar asked Apr 09 '13 13:04

tmakino


2 Answers

Is there any way I can avoid index lookup to replace the existing value?

Not that I know of - but dictionary access should be very fast unless you have a custom class that's overridden GetHashCode poorly.

If you're not seeing a performance problem because of the double lookup I'd leave it alone.

like image 116
D Stanley Avatar answered Sep 17 '22 08:09

D Stanley


You can try this out

Object value;
if (dict.TryGetValue(key, out value))
{
    if (condition)
    {
        //value.data = 0;  this copies by value so it doesn't change the existing value
        value.data = 0;
    }
}
else
{
    value.data = 0;
}

The essense of story is, the type you are fetching out is a generic type and is allocated on heap. i.e. when you fetch it out, it will come out as value. However, if you fetch out object, it will be a reference to the original allocated object and you can modify the value of a particular property of object.

like image 37
Murtuza Kabul Avatar answered Sep 21 '22 08:09

Murtuza Kabul