Collection Performance: Adding Items To a Dictionary

When incorporating items into a Dictionary, the prevalent approach in the code I review involves using the Add() method, as illustrated below:

var collection = new Dictionary<string, Person<Address>>(people.Count);

foreach (var person in personCollection)
{
    collection.Add(person.Key, person.Value);
}

An alternative approach is to utilize the TryAdd() method, which returns a Boolean, as demonstrated below:

var collection = new Dictionary<string,
                     Person<Address>>(people.Count);

foreach (var person in personCollection)
{
    _ = collection.TryAdd(person.Key, person.Value);
}

Benchmark Results

In the benchmark tests, it is evident that the overall performance of TryAdd() is only 1.003 times faster and allocates the same amount of bytes in memory as Add(). My analysis indicates that the performance degrades as more items are added to the collection. For instance, with a count of 16, TryAdd() is 1.073 times more performant. However, at the count of 2,048, the performance shows that using Add() is 1.003 times more performant.

When I setup my EditorConfig to check for these issues, it looks like this: dotnet_diagnostic.CA1864.severity = suggestion

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.

5 thoughts on “Collection Performance: Adding Items To a Dictionary

  1. This reads more like a testament to how well they’ve tried to make Add and TryAdd almost equal in performance, even though it’s much better to use TryAdd instead of ContainsKey
    +Add.

  2. You are testing two different use cases (apples vs oranges).

    Unconditionally add item to dictionary
    Check if item exists in dictionary and then if not add it

    If you want to make testing meaningful, you should add ContainsKey to #1 test

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.