Different ways to add to the dictionary

What is the difference in Dictionary.add(key, value) and Dictionary[key] = value ?

I noticed that the latest version does not throw an ArgumentException when inserting a duplicate key, but are there any reasons for preferring the first version?

Change Does anyone have an authoritative source of information about this? I tried MSDN, but this is, as always, a wild goose hunt :(

+53
optimization dictionary c #
Dec 03 '09 at 8:28
source share
7 answers

Performance is almost 100% identical. You can verify this by opening a class in Reflector.net

This is a pointer:

 public TValue this[TKey key] { get { int index = this.FindEntry(key); if (index >= 0) { return this.entries[index].value; } ThrowHelper.ThrowKeyNotFoundException(); return default(TValue); } set { this.Insert(key, value, false); } } 

And this is the Add method:

 public void Add(TKey key, TValue value) { this.Insert(key, value, true); } 

I will not publish the whole Insert method, since it is quite long, however this is a declaration of the method:

 private void Insert(TKey key, TValue value, bool add) 

And further in the function this happens:

 if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key)) { if (add) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } 

Which checks if the key already exists, and if it does, and the add parameter is true, it throws an exception.

So, for all purposes and intentions, the performance is the same.

Like some other references, the whole point is whether you need a check to try to add the same key twice.

Sorry for the long post, I hope everything is in order.

+70
Dec 03 '09 at 17:46
source share

The first version will add a new KeyValuePair key to the dictionary, tossing if the key is already in the dictionary. The second, using the index, will add a new pair if the key does not exist, but overwrite the key value if it already exists in the dictionary.

 IDictionary<string, string> strings = new Dictionary<string, string>(); strings["foo"] = "bar"; //strings["foo"] == "bar" strings["foo"] = string.Empty; //strings["foo"] == string.empty strings.Add("foo", "bar"); //throws 
+49
Dec 03 '09 at 8:31
source share

Dictionary.Add(key, value) and Dictionary[key] = value have different goals:

  • Use the Add method to add a new key / value pair; existing keys will not be replaced ( ArgumentException is ArgumentException ).
  • Use an indexer if you don't care if a key exists in the dictionary, in other words: add a key / value pair if the key is not in the dictionary, or replace the value for the specified key if the key is already in the dictionary.
+20
Dec 03 '09 at 8:36
source share

To answer the question first, we need to look at the purpose of the vocabulary and underlying technologies.

Dictionary is a list of KeyValuePair<Tkey, Tvalue> , where each value is represented by its unique key. Say we have a list of your favorite dishes. Each value (food name) is represented by its unique key (position = how much you like this food).

Code example:

 Dictionary<int, string> myDietFavorites = new Dictionary<int, string>() { { 1, "Burger"}, { 2, "Fries"}, { 3, "Donuts"} }; 

Say you want to stay healthy, you change your mind, and want to replace your favorite Burger with salad. Your list is still your favorites list; you will not change the nature of the list. Your favorite will remain number one on the list, only its value will change. This is when you call this:

 /*your key stays 1, you only replace the value assigned to this key you alter existing record in your dictionary*/ myDietFavorites[1] = "Salad"; 

But do not forget that you are a programmer, and from that moment you finish your sentences; you refuse to use emojis because they will throw a compilation error, and the entire list of favorites is index based.

Your diet has changed too! Thus, you will change your list again:

 /*you don't want to replace Salad, you want to add this new fancy 0 position to your list. It wasn't there before so you can either define it*/ myDietFavorites[0] = "Pizza"; /*or Add it*/ myDietFavorites.Add(0, "Pizza"); 

There are two possibilities with a definition: you either want to give a new definition for something that did not exist before, or you want to change a definition that already exists.

The add method allows you to add an entry, but only under one condition: the key for this definition may not exist in your dictionary.

Now we will look under the hood. When you create a dictionary, your compiler makes a reservation for the bucket (spaces in memory to store your records). The bucket does not store keys as you define them. Each key is hashed before moving into the bucket (defined by Microsoft), it is worth mentioning that the value of the part remains unchanged.

I use the CRC32 hash algorithm to simplify my example. When you define:

 myDietFavorites[0] = "Pizza"; 

What happens to the bucket: db2dc565 "Pizza" (simplified).

When you change the value with:

 myDietFavorites[0] = "Spaghetti"; 

You have x, which will again be db2dc565 , then you will find this value in your bucket to find it there. If it is there, you simply rewrite the value assigned to the key. If it is not, you will put your value in a bucket.

When you call the Add to your dictionary function, for example:

 myDietFavorite.Add(0, "Chocolate"); 

You have a hash to compare it with units in a bucket. You can put it in a bucket only if it is not there .

It is very important to know how this works, especially if you work with dictionaries like string or char. It is case sensitive due to hashing. So, for example, "name"! = "Name". Let us use our CRC32 to depict this.

Value for "name": e04112b1 Value for "Name": 1107fb5b

+6
Dec 09 '16 at 14:38
source share

Yes, this is the difference, the Add method throws an exception if the key already exists.

The reason for using the Add method is precisely this. If the dictionary should not contain the key already, you usually want an exception to let you know about the problem.

+4
Dec 03 '09 at 8:32
source share

Given the more than likely similarities in performance, use whatever is best and readable for the part of the code that you are using.

I feel the operation describing the addition, since the presence of the key is already a really rare exception, it is best represented with the addition. Semantically, this makes sense.

dict[key] = value is the best replacement. If I see this code, I would prefer that the key is already in the dictionary.

0
Dec 03 '09 at 8:29
source share

One assigns a value, and the other adds a new key and value to the dictionary.

0
Dec 31 '15 at 1:47
source share



All Articles