Dictionary ArgumentException log duplicate key: which is more efficient?
Here I am adding something to Dictionary
:
dictionary.Add(dictionaryKey, value);
if it dictionaryKey
already exists, it will be selected ArgumentException
. His post is pretty general:
An item with the same key has already been added.
If my call dictionary.Add
is inside a loop or helper function, it can be difficult to tell right away which key has already been added that is throwing this exception. I would like to know this as soon as possible and as soon as possible.
There are several options.
1)
if(dictionary.ContainsKey(dictionaryKey)
{
throw new ArgumentException($"An item with the same key ({dictionaryKey}) has already been added.");
}
dictionary.Add(dictionaryKey, value);
2)
try
{
dictionary.Add(dictionaryKey, value);
}
catch(ArgumentException argumentException)
{
throw new ArgumentException($"An item with the same key ({dictionaryKey}) has already been added.");
}
3) Another way
I know that setting up a try / catch block is a performance hit, but it seems like running dictionary.ContainsKey(dictionaryKey)
would mean an extra search every time. Which of these parameters is most effective?
source to share
Not sure where the context of this code is, but from a performance standpoint it will depend if you expect duplicate dictionaryKey
s.
If there are duplicates, I would go for the first method as it ContainsKey
is an O (1) operation and try
/ catch
carries a small performance penalty if used for control flow. Presumably, this penalty will be greater than O (1).
However, if you cannot guarantee duplicate dictionaryKey
s, the second method will be faster. Performance degradation try
/ catch
only occurs when an exception is thrown (duplicate key found). The first method will make an unnecessary call ContainsKey
. Of course, this means you don't have to wrap your code in try
/ catch
in the first place, defeating the purpose of your question.
I would go with the first method.
source to share