Dictionary ArgumentException log duplicate key: which is more performant?

Viewed 2302

Here I add something to a Dictionary:

dictionary.Add(dictionaryKey, value);

if dictionaryKey already exists, an ArgumentException will be thrown. Its message is fairly generic:

An item with the same key has already been added.

If my call to dictionary.Add is inside of a loop or a helper function, it can be hard to tell immediately what key has already been added that is throwing this exception. I would like to know this as easily and as soon as possible.

There are a few 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) Some other way

I know setting up a try/catch block takes a performance hit, but it seems running dictionary.ContainsKey(dictionaryKey) would mean an additional lookup each time too. Which of these options is most performant?

2 Answers

I would say number one is better. Because when you use the second method it will trigger an runtime error and that means it will create an additional Exception object in the memory which referenced by the variable "argumentException" in the catch phrase.

Related