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

By 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 a way to avoid index lookups to replace an existing value? I am already checking a key that exists with TryGetValue, so it seems that the waste should again get the value by index.

In a separate note, as in the else {} part of my code, it is usually considered good practice to use an indexer when adding new or replacing old values โ€‹โ€‹and adding so that it is clear that you are adding and not replacing? Or should I just use an indexer every time? The way I learned to use the dictionary, I always try TryGetValue, and in the other part I handle cases when the key is missing.

+7
source share
3 answers

Is there a way to avoid index lookups to replace an existing value?

Not that I know, but the dictionary should be very fast if you don't have a custom class that overridden GetHashCode .

If you donโ€™t see a performance issue due to double searching, I would leave it alone.

+4
source

I prefer to define convenience extension methods for such things. For example:

  public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) { TValue value; return dictionary.TryGetValue(key, out value) ? value : defaultValue; } public static TValue GetOrSet<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { return dictionary[key] = dictionary.GetValueOrDefault(key, value); } 

No need to worry about the performance of hashing and dictionary lookups - I primarily care about readability and maintainability. Using the above extension methods, this type is single-line:

 int value = dict.GetOrSet(key, 0); 

(Disclaimer: does not perform an if (condition) check - I rarely experience these scenarios)

0
source

You can try this

 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 essence of the story is that the type you are carrying is a generic type and is distributed across the heap. those. when you select it, it will come out as a value. However, if you select an object, it will be a link to the original selected object, and you can change the value of a specific property of the object.

0
source

All Articles