Search code examples
c#dictionarytry-catchbig-o

Dictionary ArgumentException log duplicate key: which is more performant?


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);
try
{
    dictionary.Add(dictionaryKey, value);
}
catch (ArgumentException argumentException)
{
    throw new ArgumentException($"An item with the same key ({dictionaryKey}) has already been added.");
}
  1. 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?


Solution

  • .NET Core introduced the TryAdd method, that allows to do it with a single lookup:

    if (!dictionary.TryAdd(key))
    {
        throw new ArgumentException($"An item with the same key ({key}) has already been added.");
    }