If i wish to put items into a System.Collections.Generic.Dictionary
, I can either Add
or set the Item
.
I know if we do Add
it checks if the key already exists and if not it throws an exception.
So when adding a ton of items, should I prefer setting Item
instead of Add
, since Add
does unnecessary checks that may actually slow things down?
Here is what happens when you set Item:
public void set_Item(TKey key, TValue value)
{
this.Insert(key, value, false);
}
Here is what happens when you add item:
public void Add(TKey key, TValue value)
{
this.Insert(key, value, true);
}
The last parameter last bool add
parameter just affects this line:
if (add)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
So if you want exception when you add a duplicate item, you need to use Add. If you want to overwrite exiting item you need to set Item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With